2014-11-09 93 views
1

explaining how to make plugins jQuery的頁面,有這段代碼:jQuery立即在CoffeeScript中調用函數?

(function ($) { 
    var shade = "#556b2f"; 

    $.fn.greenify = function() { 
    this.css("color", shade); 
    return this; 
    }; 
}(jQuery)); 

如何在CoffeeScript的代表呢?如果我試試這個:

do ($) -> 
    x = 'do nothing' 

它作爲編譯:

(function($) { 
    var x; 
    return x = 'do nothing'; 
})($); 

我無法弄清楚如何將jQuery對象傳遞給函數。

+0

這有幫助嗎? - http://coffeescriptcookbook.com/chapters/jquery/plugin – Sgnl 2014-11-09 04:56:43

+0

老實說,我不確定。它保護$別名嗎? – CaptSaltyJack 2014-11-09 04:58:37

+0

就像旁邊,你可以簡單地做'do(jQuery) - > $ = jQuery; ...' – meagar 2014-11-09 20:19:15

回答

2

你在CoffeeScript中完全一樣,你會用JavaScript來做。你只需要一些額外的括號折騰:

(($) -> 
    # plugin goes here and uses $ 
)(jQuery) 

變成這個JavaScript:

(function($) { 
    ... 
})(jQuery); 

如果你有括號的一種病態的恐懼,那麼你仍然可以使用do但你設立$別名使用默認值:

do ($ = jQuery) -> 
    # plugin code goes here 

也就是說亦譯:

(function($) { 
    ... 
})(jQuery); 
+1

嘿。病態恐懼。很好的描述。 – 2014-11-09 12:02:40

相關問題