2014-02-10 26 views
0

我有以下代碼:通話原型定義的函數

var FormCollection = function(collectionHolder, options) { 

     // defines the collection holder object (the container where each element of the collection will 
     // be added 
     this.collectionHolder = collectionHolder; 

     this.options = options; 

     // count the current form inputs we have (e.g. 2), use that as the new 
     // index when inserting a new item (e.g. 2) 
     this.collectionHolder.data('index', this.collectionHolder.find(':input').length); 

     this.addItem = collectionHolder.find('[data-collection-item-add]'); 
     this.addItem.on('click',function(e){ 
      e.preventDefault(); 

      // add a new tag form (see next code block) 
      this.add(); 
     });   
    } 

現在我要定義一個名爲click事件裏面add方法,在原型,因爲

FormCollection.prototype.add = function(){ 
    console.log(this.collectionHolder);  
    }; 

但給出一個錯誤說this.add不是一個函數。 解決此問題的最佳方法是什麼?

+0

這裏面this.addItem.on( '點擊',函數(E){});指被點擊的dom元素而不是函數。 – Abhidev

回答

0

在事件處理函數this裏面不會引用實例(在你的情況下它會引用被單擊的元素)。您可以將事件處理程序綁定到實例的實例的上下文中執行它:

this.addItem.on('click',function(e){ 
    e.preventDefault(); 

    // add a new tag form (see next code block) 
    this.add(); 
}.bind(this));  

或者你可以存儲在構造和使用,以this的引用來代替:

var _this = this; 
this.addItem.on('click',function(e){ 
    e.preventDefault(); 

    // add a new tag form (see next code block) 
    _this.add(); 
}); 
+0

我是如此專注於構造函數本身,我完全忘記了這樣的上下文一些微不足道的事情:(謝謝。 – brpaz