jQuery mit CoffeeScript

Avatar of Chris Coyier
Chris Coyier am

DigitalOcean bietet Cloud-Produkte für jede Phase Ihrer Reise. Starten Sie mit 200 $ kostenlosem Guthaben!

Ich schreibe nicht immer CoffeeScript, aber wenn ich es tue, benutze ich wahrscheinlich auch jQuery; ich vergesse immer die Syntax für Dinge. Also werde ich alles hier aufschreiben, damit ich es nachschlagen kann, bis ich es auswendig kann.

Beachten Sie, dass das kompilierte Beispiel nicht die automatische Schließung um alles enthält, was Sie in CoffeeScript bekommen.

Sicheres jQuery Closure

So können Sie das $ sicher verwenden (üblich in WordPress)

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

})(jQuery);

DOM Ready

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

Methode ohne Parameter aufrufen

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

Methode mit einem Parameter aufrufen

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

Methode mit mehreren Parametern aufrufen

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

Parameter in der anonymen Funktion

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

False zurückgeben

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

Ein einfaches Plugin

$.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
      });
    });
  }
});

Plugin verwenden

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

Ajax

Beachten Sie auch die String-Interpolation, das ist nett.

$.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);
  }
});

Animation

Zwei Wege.

div.animate {width: 200}, 2000

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

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

Animation mit Callback

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

Verkettung

Nicht viel anders.

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

Promises

Die letzte Zeile wird hier zurückgegeben, obwohl es nicht wirklich nötig ist, aber egal.

$.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);
});

Fat Arrow, um `this` zu erhalten

Andernfalls hätten Sie innerhalb von `setTimeout` keine Referenz auf den Button.

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

Hier sind alle zusammen in einem Pen, wenn Sie daran basteln möchten.