Tuesday 12 February 2013


jQuery Namespacing with on() and off() method


With jQuery 1.7, jQuery team introduced 2 new ways to attach and remove events. on() method is used for attaching events to DOM elements, and off() method is used to removed event handlers. And you should use on() and off() only to attach and remove handlers, instead of bind(), live() anddelegate(). 

Related Post:
There could be a situation where you have assigned multiple handlers on single event. For example,
1$('#btnClick').on('click', func1());
2$('#btnClick').on('click', func2());
Now, when trigger() is called on element, then both the function will get executed.
1$('#btnClick').trigger('click'); // both functions will be called.
And when off() method will be called on element, both the functions will be removed.
1$('#btnClick').off('click'); // both functions will be removed.
Now, what if when there are multiple handlers on single event and there is a need to call specific handler? In such situation, event namespacing is your friend.

Using event namespacing, at the time of creating event we can assign name. For example, "click.callFunc1" defines callFunc1 namespaces for this particular click event. Later on based on namespace, we can trigger or remove specific handler.
1$('#btnClick').on('click.callFunc1', func1());
2$('#btnClick').on('click.callFunc2', func2());
So to call func1() only, pass event.namespace in trigger() method.
1$('#btnClick').trigger('click.callFunc1'); // Only func1() will be called.
And to remove specific function, pass event.namespace in off() method.
1$('#btnClick').off('click.callFunc1'); // Only func1() will be removed.
You can also assign multiple namespaces together.

1$('#btnClick').on('click.callFunc1.callFunc2', func1());

No comments:

Post a Comment