on
can.Control.prototype.on
Bind an event handler to a Control, or rebind all event handlers on a Control.
control.on([el,] selector, eventName, func)
Parameters
-
el
=this.element
{HTMLElement | jQuery | collection | Object}
OptionalThe element to be bound. If no element is provided, the control's element is used instead.
-
selector
{CSSSelectorString}
A css selector for event delegation.
-
eventName
{String}
The event to listen for.
-
func
{function() | String}
A callback function or the String name of a control function. If a control function name is given, the control function is called back with the bound element and event as the first and second parameter. Otherwise the function is called back like a normal bind.
Returns
{Number}
The id of the binding in this._bindings
control.on()
Rebind all of a control's event handlers.
Returns
{Number}
The number of handlers bound to this Control.
on(el, selector, eventName, func)
binds an event handler for an event to a selector under the scope of the given element.this.on()
is used to rebind all event handlers when this.options has changed. It can also be used to bind or delegate from other elements or objects.Rebinding
By using templated event handlers, a control can listen to objects outside
this.element
. This is extremely common in MVC programming. For example, the following control might listen to a task model'scompleted
property and toggle a strike className like:To update the
taskstriker
's task, add a task method that updates this.options and rebinds the event handlers for the new task like:Adding new events
If events need to be bound to outside of the control and templated event handlers are not sufficient, you can call this.on to bind or delegate programmatically: