EML
EML

Reputation: 10261

jQuery UI widget 'change' event

I'm trying to maintain a widget that triggers events using one of these two lines of code:

this.element.trigger('change');  // or...
stop: function (event, ui) { that.element.change(); }

The word 'change' occurs only 4 times in the code, in one of the 2 forms above. However, I've got no idea what's going on here. There's no event handler in the change call, and there are no bind, delegate, on, or live calls, so something external is presumably setting this up. Can anyone fill me in? Are there any docs on this? Thanks.

Upvotes: 1

Views: 2971

Answers (2)

EML
EML

Reputation: 10261

The answer turned out to be simple - there was no event handler, there were no bind/etc calls, jQuery does nothing behind the scenes, so the trigger calls did nothing. I commented them out and the widget behaved exactly the same. Doh.

Upvotes: 0

Didier Ghys
Didier Ghys

Reputation: 30666

Those two lines of code simply trigger a change event to this.element using two different allowed syntax.

Using .trigger():

this.element.trigger('change');

Or using a shorthand method .change():

that.element.change();

You can actually bind an event handler to the element represented by this.element to handle this event.


Without knowing your plugin, it is difficult to answer you precisely on what is this.element.

But take the example of the autocomplete plugin. In this one, this.element is actually the input field the autocomplete plugin is applied to. If the change event was triggered like supposedly done in your question, you could bind an event handler to the input like this:

$('#myinput')
    .autocomplete()
    .bind('change', function() { });

Now if this plugin relies on the jQuery UI Widget Factory, it is advisable to use the method _trigger() to trigger events instead of the jquery .trigger().

Using _trigger() will make sure to execute any callback defined in the plugin's option with a correct context and also trigger that event for this.element (like above). So you could have:

$('#myinput')
    .somePlugin({
        change: function(e, someData) {
            // "this" here will be `this.element´
        }
    })
    .bind('change', function() { ... });

Upvotes: 2

Related Questions