1

I have a widget defined like so:

$.widget("ui.mywidget", {
    _init: function() {
        this.element.bind("keyup", function(event) {
            alert(this.options);
            alert(this.options.timeout);
        });
    }
});

And trying to call it like so:

$("input.mywidget").mywidget({timeout: 5});

I also redefined the bind method using the this.element.keyup(function(event) { ... }) style: no difference.

But, in the keyup bind, this.options (and referencing it just as options) both yield undefined. I thought the UI widget framework allowed this type of abstraction; am I doing something wrong?

3 Answers 3

2

When inside bind(), this changes to refer to the object that the event is raised on. Try:

$.widget("ui.mywidget", {
    _init: function(options) {
        var opts = this.options;
        this.element.bind("keyup", function(event) {
            alert(opts);
            alert(opts.timeout);
        });
    }
});
2
  • 2
    In the widget framework is the _create() or _init() method more appropriate for this kind of binding?
    – Wells
    Commented Sep 15, 2010 at 22:31
  • I'm not familiar enough with the framework to be able to say, sorry!
    – DMI
    Commented Sep 15, 2010 at 22:36
2

What @Dave said is right. You can also set "this" to a variable rather than using options as an argument to the init function. Here is how I see it implemented often:

$.widget("ui.mywidget", {
    options: {
        timeout: 100
    },
    _init: function() {
        var self = this;
        self.element.bind("keyup", function(event) {
            alert(self.options);
            alert(self.options.timeout);
        });
    }
});
1

Why stop there? Check out $.proxy and write better code

$.widget("ui.mywidget", {
    _create: function() {

        //Under this syntax, _omgAlertsRule must be a method of 'this'
        this.element.bind("keyup", $.proxy( this, '_omgAlertsRule' ) );
    },
    _omgAlertsRule: function( event ){

        alert(this.options);
        alert(this.options.timeout);
    }
});

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.