2010-12-10 88 views
0

我使用的是原型1.7,並構建了一個基本上需要divs列表並構建標籤界面的類。在回調中訪問類方法的正確方法[原型]

var tabs = Class.create({ 
    initialize: function(container, options) { 
     this.options = Object.extend({ 
      // additional options 
      tabsRendered: null, 
     }, options || {}); 

     // init code 

     if(this.options.tabsRendered) { 
      this.options.tabsRendered(); 
     } 
    }, 

    // additional methods 

    setCurrent: function(link){ 
     //adds a .current class to tab clicked and its corresponding section 
    } 
}; 

new vtabs('products', { 
    tabsRendered: function(){ 
     if(window.location.hash != "") { 
      var link = $$('a[href$="' + window.location.hash + '"]'); 
      this.setCurrent(link); 
     } 
    } 
}); 

我的問題涉及到我的tabsRendered自定義回調。當回調運行時,this.setCurrent(link)什麼都不做。

如果我通過這個進入回調,我的自定義回調按預期工作。

if(this.options.tabsRendered) { 
    this.options.tabsRendered(this); 
} 

我的猜測是,通過步入回調是不是最好的做法。那麼,我將如何允許從回調中訪問方法?

感謝

回答

2

問題是tabsRendered綁定。通過Prototype,您必須使用bind()綁定匿名函數。後// init code做:

if (Object.isFunction(this.options.tabsRendered)) 
    this.options.tabsRendered = this.options.tabsRendered.bind(this); 

之後,你可以調用this.options.tabsRendered()而且一旦匿名函數中,this將引用正確的對象。有關綁定的詳細信息,請參見the Prototype API docs

編輯:正如評論:匿名函數不是唯一受影響的是正確的。它是函數被定義的範圍中的this

+0

+1,但函數是匿名還是無關緊要,與綁定沒有任何關係。另外,'bind'只是其中的幾種方法之一(儘管它是一個很好的方法)。有關'this'的更多信息並確保您保留它:http://blog.niftysnippets.org/2008/04/you-must-remember-this.html和http://blog.niftysnippets.org/2008/03/ mythical-methods.html – 2010-12-10 18:17:33

+0

是的。我會重新相聚。 – 2010-12-10 18:21:01

+0

謝謝goreSplatter,你的建議幫了很大忙。奇怪的是,「Prototype.isFunction(this.option.tabsRendered)」不起作用。事實上,它導致腳本停止執行。 – jbarreiros 2010-12-10 19:41:00