CoffeeScript jQuery

使用CoffeeScript編寫jQuery

取得某個元素

1
toolbar = $('#toolbar')
1
2
var toolbar;
toolbar = $('#toolbar');

document.ready

寫法1

1
2
$().ready = ->
alert "Hello CoffeeScript"
1
2
3
$().ready = function() {
return alert("Hello CoffeeScript");
};

寫法2

1
2
$ ->
alert "Hello CoffeeScript"
1
2
3
$(function() {
return alert("Hello CoffeeScript");
});

click

1
2
3
$ ->
$('p').click ->
$(@).html "clicked"
1
2
3
4
5
$(function() {
return $('p').click(function() {
return $(this).html("clicked");
});
});

擴充jQuery

1
2
3
4
5
6
7
8
9
$.fn.extend
min: (a, b) ->
if a > b then b else a
max: (a, b) ->
if a > b then a else b
# 2
console.log $(window).min 2,5
# 5
console.log $(window).max 2,5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$.fn.extend({
min: function(a, b) {
if (a > b) {
return b;
} else {
return a;
}
},
max: function(a, b) {
if (a > b) {
return a;
} else {
return b;
}
}
});
console.log($(window).min(2, 5));
console.log($(window).max(2, 5));