2012-08-12 37 views
1

我正在學習使用widget-factory模式編寫jquery-ui插件。爲了組織更清潔,我在對象字面量中定義了一些幫助器方法,這些方法被傳遞給$.widget。我想訪問這些助手中的選項對象。例如在下面的樣板中,如何訪問_helper()內的選項對象?jQuery-ui:我如何從私有函數中訪問選項

;(function ($, window, document, undefined) { 

    $.widget("namespace.widgetName" , { 

     options: { 
      someValue: null 
     }, 

     _create: function() { 
      // initialize something.... 
     }, 

     destroy: function() { 

      $.Widget.prototype.destroy.call(this); 
     }, 

     _helper: function() { 
      // I want to access options here. 
      // "this" points to the dom element, 
      // not this object literal, therefore this.options wont work 
      console.log('methodB called'); 
     }, 

     _setOption: function (key, value) { 
      switch (key) { 
      case "someValue": 
       //this.options.someValue = doSomethingWith(value); 
       break; 
      default: 
       //this.options[ key ] = value; 
       break; 
      } 
      $.Widget.prototype._setOption.apply(this, arguments); 
     } 
    }); 

})(jQuery, window, document); 

謝謝。

+0

具有前導下劃線的方法是否被widget工廠認爲是私有的?那你怎麼叫'_helper'? – 2012-08-12 03:39:45

+0

那麼,在_create方法中,這指向對象字面量(第二個參數爲$ .widget),因此可以在_create內部調用this._helper() – 2012-08-12 03:49:26

+0

但是,你說''this'指向dom元素'那麼'._helper()'調用的樣子是什麼? '_create'是一個特殊的方法,它是widget界面的一部分。 – 2012-08-12 03:54:59

回答

1

所以你是你的_create內這樣做:

$(some_selector).click(this._helper) 

,你想this_helper裏面是thisthis._helper(即你的widget)。

有各種不同的解決方案:

  1. 你可以使用$.proxy

    $(some_selector).click($.bind(this._helper, this)); 
    

    下劃線也有_.bind,有一個本地Function.bind如果你不擔心JavaScript版本的問題)。其他庫將有自己的函數綁定工具。你已經有了jQuery,所以$.proxy已經可用並且可移植了。

  2. 你可以使用標準的var _this = this;招代理_helper自稱:

    var _this = this; 
    $(some_selector).click(function() { _this._helper() }); 
    
  3. 您可以使用eventData form of click

    $(some_selector).click({ self: this }, this._helper); 
    

    ,然後在_helper

    _helper: function(ev) { 
        var self = ev.data.self; 
        // 'self' is the 'this' you're looking for. 
        ... 
    } 
    
+0

與此同時,我嘗試將選項作爲event.data的一部分進行綁定,並按預期工作。但是,感謝代理解決方案 - 它幫助我添加一個技巧來增加我的jquery技能:)。已經接受你的回答 – 2012-08-12 20:20:20

+1

@ Ya.Perelman:對,'eventData'是另一種選擇,爲了完整性我會加上。我最近做了很多骨幹的東西,所以我的大腦總是爲綁定解決方案而努力。 – 2012-08-12 20:30:31

相關問題