Ticket #12031 (assigned feature)
Allow objects as event handlers
| Reported by: | petka_antonov@… | Owned by: | rwaldron |
|---|---|---|---|
| Priority: | low | Milestone: | None |
| Component: | event | Version: | 1.7.2 |
| Keywords: | Cc: | ||
| Blocking: | Blocked by: |
Description
Doing OOP with jQuery events requires a lot of $.proxy boilerplate. the .addEventListener interface allows passing an object as a handler like so:
function SomeWidget( elem ) {
this.elem = elem;
}
SomeWidget.prototype = {
constructor: SomeWidget,
renderTo: function( target ) {
$(target).append(this.elem);
this.elem.addEventListener( "click", this );
this.elem.addEventListener( "mousemove", this );
},
mousemove: function( e ) {
},
click: function( e ) {
},
handleEvent: function( e ) {
return this[e.type].apply( this, arguments );
}
};
With jQuery you have to do this:
function SomeWidget( elem ) {
this.elem = elem;
//Each method needs to be bound to the instance. This also has overhead of creating many functions.
this.mousemove = $.proxy( this.mousemove, this );
this.click = $.proxy( this.click, this );
}
SomeWidget.prototype = {
constructor: SomeWidget,
renderTo: function( target ) {
$(target).append(this.elem);
$(this.elem).on( {
click: this.click,
mousemove: this.mousemove
});
},
mousemove: function( e ) {
},
click: function( e ) {
}
};
With jQuery supporting objects as event handlers, it would work like:
function SomeWidget( elem ) {
this.elem = elem;
}
SomeWidget.prototype = {
constructor: SomeWidget,
renderTo: function( target ) {
$(target).append(this.elem);
$(this.elem).on( "click mousemove", this );
},
mousemove: function( e ) {
},
click: function( e ) {
},
handleEvent: function( e ) {
return this[e.type].apply( this, arguments );
}
};
And that's it. No $.proxy hacks, no redundant creation of functions just to retain binding.
Change History
comment:3 Changed 11 months ago by rwaldron
I'm into this
http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener
@dmethvin - if you don't mind, I'd like to prototype this one :)
comment:4 Changed 11 months ago by rwaldron
- Owner set to rwaldron
- Status changed from open to assigned
comment:5 Changed 11 months ago by rwaldron
note to self...
.on({ click: fn })
Has to support handling:
// delegated events
.on({ click: fn }, "div");
// data object events
.on({ click: fn }, "div", dataobject);
Please follow the bug reporting guidlines and use jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.

Worth thinking about so I'll leave it open.