CoffeeScript 与 jQuery

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 200 美元的免费额度!

我并不总是编写 CoffeeScript,但如果我编写,我可能也会使用 jQuery;我总是忘记一些东西的语法。因此,我将在这里全部写下来,以便在记住之前可以参考。

请注意,编译后的示例不包括 CoffeeScript 中自动生成的封闭函数。

安全的 jQuery 封闭函数

这样您就可以安全地使用 $(在 WordPress 中很常见)

(($) ->
  
) jQuery
(function($) {

})(jQuery);

DOM 就绪

$ ->
  console.log("DOM is ready")
$(function() {
  return console.log("DOM is ready");
});

调用无参数的方法

$(".submit").click ->
  console.log("submitted!")
$(".submit").click(function() {
  return console.log("submitted!");
});

调用一个参数的方法

$(".button").on "click", ->
  console.log("button clicked!")
$(".button").on("click", function() {
  return console.log("button clicked!");
});

调用多个参数的方法

$(document).on "click", ".button2", ->
  console.log("delegated button click!")
$(document).on("click", ".button2", function() {
   return console.log("delegated button click!");
});

匿名函数中的参数

$(".button").on "click", (event) ->
  console.log("button clicked!")
  event.preventDefault()
$(".button").on("click", function(event) {
  console.log("button clicked!");
  return event.preventDefault();
});

返回 False

$(".button").on "click", ->
  false
$(".button").on("click", function() {
  return false;
});

一个简单的插件

$.fn.extend
  makeColor: (options) ->
    settings = 
      option1: "red"
    
    settings = $.extend settings, options
    
    return @each () ->
      $(this).css
        color: settings.color
$.fn.extend({
  makeColor: function(options) {
    var settings;
    settings = {
      option1: "red"
    };
    settings = $.extend(settings, options);
    return this.each(function() {
      return $(this).css({
        color: settings.color
      });
    });
  }
});

使用插件

$("a").makeColor
   color: "green"
$("a").makeColor({
  color: "green"
});

Ajax

请注意那里的字符串插值,这也很不错。

$.ajax
   url: "some.html"
   dataType: "html"
   error: (jqXHR, textStatus, errorThrown) ->
     $('body').append "AJAX Error: #{textStatus}"
   success: (data, textStatus, jqXHR) ->
     $('body').append "Successful AJAX call: #{data}"
$.ajax({
  url: "some.html",
  dataType: "html",
  error: function(jqXHR, textStatus, errorThrown) {
    return $('body').append("AJAX Error: " + textStatus);
  },
  success: function(data, textStatus, jqXHR) {
    return $('body').append("Successful AJAX call: " + data);
  }
});

动画

两种方法。

div.animate {width: 200}, 2000

div.animate
  width: 200
  height: 200
  2000
div.animate({
  width: 200
}, 2000);

div.animate({
  width: 200,
  height: 200
}, 2000);

带回调函数的动画

div.animate
  color: red
  2000
  ->
    doSomething()
div.animate({
  color: red
}, 2000, function() {
  return doSomething();
});

链式调用

差别不大。

$("input")
  .val("")
  .css
    'z-index': 5
  .removeClass "fart"
$("input").val("").css({
  'z-index': 5
}).removeClass("fart");

Promise

虽然这里最后一行被返回了,但实际上并不需要,不过无所谓。

$.when(
  $.get("/feature/", (html) ->
    globalStore.html = html;
  ),
  $.get("/style.css", (css) ->
    globalStore.css = css;
  )
).then -> 
  $("<style />").html(globalStore.css).appendTo("head")
  $("body").append(globalStore.html)
$.when($.get("/feature/", function(html) {
  return globalStore.html = html;
}), $.get("/style.css", function(css) {
  return globalStore.css = css;
})).then(function() {
  $("<style />").html(globalStore.css).appendTo("head");
  return $("body").append(globalStore.html);
});

使用胖箭头保留 `this`

否则,在 `setTimeout` 内部,您将无法引用按钮。

$(".button").click ->
  setTimeout ( =>
    $(@).slideUp()
  ), 500
$(".button").click(function() {
  return setTimeout(((function(_this) {
    return function() {
      return $(_this).slideUp();
    };
  })(this)), 500);
});

如果您想尝试一下,这里有一个 Pen 中的完整代码