1

ウィジェットファクトリを作成しましたが、パブリックメソッドでそのオプションまたはメソッドにアクセスしたいのですが、エラー「142 Uncaught TypeError:Object hasnomethod」または「cannotreadproperty」が返されます。正しくアクセスするには?

次に例を示します。

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");
});

_createメソッドのオプションにアクセスすると、正常に機能します。よろしくお願いします。

4

1 に答える 1

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.

これが完了すると、コードは期待どおりに機能します。この fiddleでテストできます。

編集:コメントで説明されている問題に関しては、setInterval()がコールバック関数を呼び出すときに、オブジェクトではなくthisグローバル オブジェクト (windowこの場合) にバインドされるためです。$.proxy()でこの問題を回避できます。

pubFunction : function() {
  setInterval($.proxy(this.calledFunction, this), 1000);
},
于 2012-11-03T07:40:09.453 に答える