Writing a jquery plugin in coffeescript - how to get “(function($)” and “(jQuery)”?

后端 未结 8 1130
温柔的废话
温柔的废话 2020-12-13 12:55

I am writing a jquery plugin in coffeescript but am not sure how to get the function wrapper part right.

My coffeescript starts with this:

$.fn.exten         


        
相关标签:
8条回答
  • 2020-12-13 13:31

    You could simply add the closure yourself and compile it with the --bare flag.

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

    (($) ->
      # some code here
    )(jQuery)
    
    0 讨论(0)
  • 2020-12-13 13:32

    The answer is that you don't need to call it like that in CoffeeScript -- your script is already safely wrapped in a closure, so there's no need for jQuery-passed-in-as-a-parameter-tricks. Just write:

    $ = jQuery
    

    ... at the top of your script, and you're good to go.

    0 讨论(0)
  • 2020-12-13 13:32

    The easiest way is to extend $.fn object

    Simple jQuery plugin can be written in CoffeeScript as follows:

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

    it will compile to

    (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);
    
    0 讨论(0)
  • 2020-12-13 13:36

    UPDATE/EDIT: Yep, as per Jeremy's explanation:

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

    compiles to:

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

    Which works just fine as a jQuery plugin: $('body').myPlugin();

    Original:

    Okay, i think I may getting close on this one, let me know if it helps.

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

    renders into:

    (function() {
      (function($) {
        return $.fn.extend = {
          myplugin: function() {},
          this.each: function() {}
        };
      })(jQuery);
    }).call(this);
    
    0 讨论(0)
  • 2020-12-13 13:37

    Unless you're using the --bare flag in the compiler, the

    $ = jQuery
    

    solution is best. If you are, then with the new do keyword, you can write

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

    thus creating the desired scope while avoiding a mess o' parentheses.

    0 讨论(0)
  • 2020-12-13 13:43

    You should take a look at the CoffeeScript version of jQuery Boilerplate ~ https://github.com/zenorocha/jquery-boilerplate/blob/master/jquery.boilerplate.coffee

    0 讨论(0)
提交回复
热议问题