2010-12-10 2 views
0

프로토 타입 1.7을 사용하고 있으며 본질적으로 div 목록을 가져 와서 탭 인터페이스를 작성하는 클래스를 작성하고 있습니다.올바른 방법으로 콜백의 클래스 메소드에 액세스합니다. [프로토 타입]

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을 참조하십시오.

EDIT : 주석 처리 : 익명의 기능 만 영향을받는 것은 아닙니다. 범위 에서을 정의한 것은 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 –

+0

예. 나는 다시 생각할 것이다. –

+0

고맙습니다. 스플래터, 당신의 제안이 많은 도움이되었습니다. 흥미롭게도 "Prototype.isFunction (this.option.tabsRendered)"가 작동하지 않았습니다. 사실 스크립트가 실행을 멈추게 만들었습니다. – jbarreiros