views:

30

answers:

2

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?

+1  A: 

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);
        });
    }
});
Dave
In the widget framework is the `_create()` or `_init()` method more appropriate for this kind of binding?
Wells
I'm not familiar enough with the framework to be able to say, sorry!
Dave
A: 

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