36

我正在咖啡脚本中编写一个 jquery 插件,但不确定如何正确获取函数包装器部分。

我的咖啡脚本从这个开始:

$.fn.extend({
    myplugin: ->
        @each ->

它使用函数包装器创建 javascript:

(function() {
  $.fn.extend({
      myplugin: function() {
          return this.each(function() {

但我想要一个像这样传入的'$':

(function($) {
  $.fn.extend({

类似的结局我有......在coffeescript中没有什么特别的。
我在javascript中得到这个:

})();

但想要这样:

})(jQuery);

有谁知道如何使用 coffeescript 编译器来实现这一点?或者在咖啡脚本中完成这项工作的最佳方法是什么?

4

8 回答 8

54

答案是你不需要像在 CoffeeScript 中那样调用它——你的脚本已经安全地包装在一个闭包中,所以不需要 jQuery-passed-in-as-a-parameter-tricks。写吧:

$ = jQuery

...在你的脚本的顶部,你很高兴。

于 2010-12-26T15:52:09.267 回答
19

除非您--bare在编译器中使用该标志,否则

$ = jQuery

解决方案是最好的。如果你,那么使用 newdo关键字,你可以写

do ($ = jQuery) ->
   # plugin code...

从而创建所需的范围,同时避免混乱的括号。

于 2010-12-27T01:04:08.230 回答
6

更新/编辑:是的,根据杰里米的解释:

$ = jQuery

$.fn.myPlugin = () ->
  console.log('test fired')

编译为:

(function() {
  var $;
  $ = jQuery;
  $.fn.myPlugin = function() {
    return console.log('test fired');
  };
}).call(this);

作为 jQuery 插件工作得很好:$('body').myPlugin();

原来的:

好的,我想我可能会接近这个,如果有帮助,请告诉我。

(($) ->
  $.fn.extend =
    myplugin: ->
    @each: ->
)(jQuery)

呈现为:

(function() {
  (function($) {
    return $.fn.extend = {
      myplugin: function() {},
      this.each: function() {}
    };
  })(jQuery);
}).call(this);
于 2010-12-26T15:32:39.857 回答
3

最简单的方法是扩展$.fn对象

可以用 CoffeeScript 编写简单的 jQuery 插件,如下所示:

$.extend $.fn,

  disable: ->
    @each ->
      e = $(this)
      e.attr("disabled", "disabled") if e.is("button") or e.is("input")

它将编译为

(function() {
  $.extend($.fn, {
    disable: function() {
      return this.each(function() {
        var e;
        e = $(this);
        if (e.is("button") || e.is("input")) {
          return e.attr("disabled", "disabled");
        }
      });
    }
  });
}).call(this);
于 2011-04-12T16:40:21.107 回答
2

你应该看看 jQuery Boilerplate 的 CoffeeScript 版本 ~ https://github.com/zenorocha/jquery-boilerplate/blob/master/jquery.boilerplate.coffee

于 2011-10-14T12:22:19.280 回答
2

虽然这篇文章很旧,但我发现它很有用。这是适合我的咖啡脚本代码。

$ -> 
    $('.my-class').hello()

$.fn.hello=-> 
    @each -> 
        $(@).append $ '<div>Hello</div>'

注意:您不需要声明$变量,您可以直接使用它。

于 2013-05-20T11:01:09.813 回答
1

--bare您可以简单地自己添加闭包并使用标志编译它。

coffee -w -c --bare jquery.plugin.coffee

(($) ->
  # some code here
)(jQuery)
于 2011-12-07T20:00:19.003 回答
0

简单明了

cleanFadeIn为了在 jQuery 对象上添加我自己的方法,这就是我所要做的。它还返回用于链接的对象:

$.fn.extend
  cleanFadeIn: ->                     # $('.notice').cleanFadeIn
    return $(@).each ->               # returns the objects for easy chaining.
      $(@).slideDown 'slow', ->
        $(@).fadeTo 'slow', 1
于 2014-09-04T16:19:41.267 回答