1

我创建了一些小部件工厂,我想在公共方法中访问它的选项或方法,但它返回错误“142 Uncaught TypeError: Object has no method”或“无法读取属性”。如何正确访问?

这是示例:

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 回答