Question

I have created some widget factory and i want to access it's options or method in public method, but it return error "142 Uncaught TypeError: Object has no method" or "cannot read property". How to access it correctly?

Here is the example:

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

If I access the options in the _create method it's work fine. Thank you before.

Was it helpful?

Solution

Most of your code is fine, but you have syntax errors near the end of the anonymous function. The call to $.widget() does not end properly, and the anonymous function itself is never called.

Try:

(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.

Once this is done, the code works as expected. You can test it in this fiddle.

EDIT: Concerning the issue described in your comment, that's because when setInterval() invokes your callback function, this is bound to the global object (window in our case), not to your object. You can work around that problem with $.proxy():

pubFunction : function() {
  setInterval($.proxy(this.calledFunction, this), 1000);
},
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top