2014-02-10 3 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(); 
     });   
    } 

지금 내가 클릭 이벤트 내에서 호출 추가 방법을 정의하려면, 프로토 타입을

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

그러나 때문에 this.add가 함수가 아니라는 오류를줍니다. 이 문제를 해결하는 가장 좋은 방법은 무엇입니까?

+0

이 : 대신 생성자 및 사용 this에 대한 참조를 저장할 수 있습니다

this.addItem.on('click',function(e){ e.preventDefault(); // add a new tag form (see next code block) this.add(); }.bind(this)); 

또는 : 당신은 인스턴스의 맥락에서 그것을 실행하는 인스턴스에 이벤트 처리기를 바인딩 할 수 있습니다 this.addItem.on ('click', function (e) {}); 클릭 한 DOM 요소를 나타내며 함수는 참조하지 않습니다. – Abhidev

답변

0

이벤트 처리기 함수 내에서 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