Skip to content

Commit 899ddb2

Browse files
committed
Merge pull request coffeescript-cookbook#12 from house9/master
new recipe: jquery ajax
2 parents aa81c4c + f2d2d7c commit 899ddb2

File tree

3 files changed

+63
-1
lines changed

3 files changed

+63
-1
lines changed

chapters/jquery/ajax.textile

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
---
2+
layout: recipe
3+
title: Ajax
4+
chapter: jQuery
5+
---
6+
7+
h2. Problem
8+
9+
You need to make an ajax request using jQuery.
10+
11+
12+
h2. Solution
13+
14+
{% highlight coffeescript %}
15+
jQuery ->
16+
console.log "document loaded"
17+
$('form').submit (e) ->
18+
console.log "form submit"
19+
e.preventDefault()
20+
form = this
21+
22+
$.ajax
23+
type: "POST"
24+
url: $(form).attr('action')
25+
data: $(form).serialize()
26+
success: ->
27+
console.log("success")
28+
{% endhighlight %}
29+
30+
31+
h2. Discussion
32+
33+
The jQuery and $ variables can be used interchangeably. See also "Callback bindings":../jquery/callback-bindings-jquery.
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
---
2+
layout: recipe
3+
title: Create an object literal if it does not already exist
4+
chapter: Objects
5+
---
6+
7+
h2. Problem
8+
9+
You want to initialize an object literal, but you do not want to overwrite the object if it already exists.
10+
11+
12+
h2. Solution
13+
14+
Use the Existential operator
15+
16+
{% highlight coffeescript %}
17+
window.MY_NAMESPACE ?= {}
18+
{% endhighlight %}
19+
20+
21+
h2. Discussion
22+
23+
This is equivalent to the following JavaScript:
24+
25+
{% highlight javascript %}
26+
window.MY_NAMESPACE = window.MY_NAMESPACE || {};
27+
{% endhighlight %}
28+
29+
Common JavaScript technique, using object literal to define a namespace. This saves us from clobbering the namespace if it already exists.

wanted-recipes.textile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ console.log [1,2,3,4,5].map (x) ->
108108

109109
h2. jQuery
110110

111-
* jQuery AJAX from CS
111+
*
112112

113113
h2. Regular Expressions
114114

0 commit comments

Comments
 (0)