2012-04-12 79 views
1

我知道這個問題已經被問了好幾次了,但是所有的答案都讓我困惑,因爲我不確定如何讓coffeescript代碼編譯到指定的jquery代碼中。從插件外部訪問jquery/coffeescript插件的方法

這是我到目前爲止有:

pluginName = 'tagbox' 

states = 
    none: 0 
    typing: 1 
    altering: 2   

defaults = 
    editing: true 
    tags: [] 

class Plugin 
    constructor: (@element, options) -> 
    @options = $.extend {}, defaults, options 
    @_defaults = defaults 
    @_states = states 
    @state = states.none 
    @_name = 'tagbox' 
    @currentTag = $("<div class='ui-individualtag'></div>") 

    # this is the public method I want 
    setCurrentTag: (tagText) -> 
    @currentTag.text(tagText) 

$.fn[pluginName] = (options) -> 
    @each -> 
    if !$.data(this, "plugin_#{pluginName}") 
     $.data(@, "plugin_#{pluginName}", new Plugin(@, options)) 
)(jQuery, window, document) 

然後在另一個劇本,我希望能夠訪問setCurrentTag方法是這樣的:

tagbox = $('#tagbox').tagbox() 
tagbox.setCurrentTag("hello world") 

讓我知道,如果它將有助於展示這個編譯成jQuery的東西。

+0

@RicardoTomasi:還有jQuery-UI風格的$(x).tagbox('setCurrentTag','hello world')'。這與我所見過的標準方法最接近,避免了在保留鏈接的同時污染名稱空間。 – 2012-04-12 20:46:10

+0

@ muistooshort是的,但他要求其他。這是一個混亂的方式:) – 2012-04-12 22:02:45

回答

2

您的問題是tagbox

tagbox = $('#tagbox').tagbox() 

將是一個jQuery對象,並且不會有setCurrentTag方法。你不想試圖改變它,因爲這會打破常見的jQuery鏈接行爲。要解決這個問題的方法之一是給tagbox插件足夠的情報來分析它的參數,這樣就可以在傳遞一個方法名稱:

$('#tagbox').tagbox('setCurrentTag', 'hello world') 

這是做法,jQuery-UI需要,所以應該很熟悉了很多jQuery人。

所有你需要做的就是修改$.fn.tagbox看起來更像是這樣的:

$.fn[pluginName] = (options = {}) -> 
    if $.isPlainObject options 
    @each -> 
     if !$.data(@, "plugin_#{pluginName}") 
     $.data(@, "plugin_#{pluginName}", new Plugin(@, options)) 
    else 
    args = Array.prototype.slice.call(arguments); 
    @each -> 
     p = $.data(@, "plugin_#{pluginName}") 
     p[args[0]](args[1]) 

演示:http://jsfiddle.net/ambiguous/q2U7d/

需要注意以下幾點:

  1. 我添加默認((options = {}) ->),以便options將永遠在那裏。
  2. 我們可以檢查我們是否有使用$.isPlainObject的選項對象,如果沒有選項,那麼我們可以假設我們正在進行方法調用。這就是爲什麼我們要在的默認值。
  3. 我們使用Array.prototype.slice.call作爲hack來將類似數組的arguments轉換爲真實數組,以使其更易於使用。我們沒有做到這一點,但它可以節省一些混亂,如果我們要使用Array方法(如pop),我們需要@each回調反正裏到外arguments參考:arguments是上下文就像this是敏感(咖啡| JAVA)腳本。