# 9jQuery
### AJAX
### 問題
你想要使用 jQuery 來調用 AJAX。
### 解決方案
~~~
$ ?= require 'jquery' # 由于 Node.js 的兼容性
?
$(document).ready ->
# 基本示例
$.get '/', (data) ->
$('body').append "Successfully got the page."
?
$.post '/',
userName: 'John Doe'
favoriteFlavor: 'Mint'
(data) -> $('body').append "Successfully posted to the page."
?
# 高級設置
$.ajax '/',
type: 'GET'
dataType: 'html'
error: (jqXHR, textStatus, errorThrown) ->
$('body').append "AJAX Error: #{textStatus}"
success: (data, textStatus, jqXHR) ->
$('body').append "Successful AJAX call: #{data}"
~~~
jQuery 1.5 和更新版本都增加了一種新補充的 API ,用于處理不同的回調。
~~~
request = $.get '/'
request.success (data) -> $('body').append "Successfully got the page again."
request.error (jqXHR, textStatus, errorThrown) -> $('body').append "AJAX Error: ${textStatus}."
~~~
### 討論
其中的 jQuery 和 $ 變量可以互換使用。另請參閱[ Callback bindings ](http://coffeescript-cookbook.github.io/chapters/jquery/callback-bindings-jquery)。
### 回調綁定
### 問題
你想要把一個回調與一個對象綁定在一起。
### 解決方案
~~~
$ ->
class Basket
constructor: () ->
@products = []
?
$('.product').click (event) =>
@add $(event.currentTarget).attr 'id'
?
add: (product) ->
@products.push product
console.log @products
?
new Basket()
~~~
### 討論
通過使用等號箭頭(=>)取代正常箭頭(->),函數將會自動與對象綁定,并可以訪問 @- 可變量。
### 創建 jQuery 插件
### 問題
你想用 CoffeeScript 來創建 jQuery 插件。
### 解決方案
~~~
# 參考 jQuery
?
$ = jQuery
?
# 給 jQuery 添加插件對象
?
$.fn.extend
# 把 pluginName 改成你的插件名字。
pluginName: (options) ->
# 默認設置
settings =
option1: true
option2: false
debug: false
?
# 合并選項與默認設置。
settings = $.extend settings, options
?
# Simple logger.
log = (msg) ->
console?.log msg if settings.debug
?
# _Insert magic here._
return @each ()->
log "Preparing magic show."
# 你可以使用你的設置了。
log "Option 1 value: #{settings.option1}"
~~~
### 討論
這里有幾個關于如何使用新插件的例子。
### JavaScript
~~~
$("body").pluginName({
debug: true
});
~~~
### CoffeeScript
~~~
$("body").pluginName
debug: true
~~~