2012-11-03 2 views
1

일부 위젯 팩터 리를 만들었으며 public 메서드에서 옵션 또는 메서드에 액세스하려고하지만 "142 Uncaught TypeError : Object has not method"또는 " 속성을 읽을 수 없습니다 ". 올바르게 액세스하는 방법? 나는 _create 방법의 옵션을 액세스하는 경우이 작업 괜찮jQuery 위젯 팩토리 액세스 옵션 및 메서드 public 메서드에서 setInterval

function($){ 
    $.widget("demo.myWidget",{ 
    options:{ 
     myVar:0 
    }, 
    _create:function(){ 
     //this line work in here 
     alert(this.options.myVar); 
    }, 
    calledFunction : function(){ 
     alert(this._getVar()); 
    }, 
    pubFunction : function(){ 
     setInterval(this.calledFunction, 1000); 
    }, 
    _getVar : function(){ 
     return this.options.myVar; 
    } 
    }); 
}(jQuery)); 

$(document).ready(function(){ 
    $("selector").myWidget(); 
    $("selector").myWidget("pubFunction"); 
}); 

: 여기

은 예입니다. 전에 고마워.

답변

2

대부분의 코드는 정상이지만 익명 기능이 끝날 무렵에는 구문 오류가 있습니다. $.widget()에 대한 호출이 제대로 끝나지 않으며 익명 함수 자체가 호출되지 않습니다.

시도 :이 일단

(function($) { 
    $.widget("demo.myWidget", { 
    options: { 
     myVar:0 
    }, 
    _create: function() { 
     //this line work in here 
     alert(this.options.myVar); 
    }, 
    calledFunction: function() { 
     alert(this._getVar()); 
    }, 
    pubFunction: function() { 
     this.setInterval(this.calledFunction, 1000); 
    }, 
    _getVar : function() { 
     return this.options.myVar; 
    } 
    });  // <-- End call to $.widget(). 
})(jQuery); // <-- End anonymous function and call it with the jQuery object. 

완료, 코드 예상대로 작동합니다. this fiddle에서 테스트 할 수 있습니다.

편집 : setInterval()가 콜백 함수를 호출 할 때, this가 아닌 객체에, (우리의 경우 window) 전역 객체에 바인딩되어 있기 때문에은 당신의 코멘트에 설명 된 문제에 관하여, 그입니다. $.proxy()으로이 문제를 해결할 수 있습니다.

pubFunction : function() { 
    setInterval($.proxy(this.calledFunction, this), 1000); 
}, 
+0

oops, 최종 통화를 추가하는 것을 잊어 버렸습니다. 하지만 setInterval 후에 옵션에 액세스하면 여전히 작동하지 않습니다. 상기시켜 주셔서 감사합니다. – deka

+0

실제로'setInterval()'에 추가적인 문제가 있습니다. 내 업데이트 답변을 참조하십시오. –

+0

대단히 감사합니다. 지금 잘 작동합니다. – deka