Reputation: 2743
I have an object, and when that object is instantiated, it attaches a click event handler to the <body>
. (The process of attaching happens within that object's definition)
This object is instantiated when the URL is changed (when the user navigates to another page).
There is always one type of this object 'per page', and as previously noted, it reinstantiates when the pange is changed, and the old object will no longer exist.
The attaching process looks like this:
var doc = $(document.body);
doc.off('click');
doc.on('click', function(){
do_stuff();
});
I am using this because I noticed that if simply attach the event handler, omitting the .off()
, the handler will fire more times on a simple click as I navigate through the site (because it was attached/registered with every instantiation of that object).
Now, I could move this attachment process somewhere else, for example in the code section where the instantiation occurs, so it won't depend on that object and assure that the handler will be attached only once, but that would deprive me of access to some local variables and I would have to make them accessible to that code section.
My question is: Does this cost a lot performance-wise? I have noticed some posts here, on stackoverflow, emphasizing this is not optimal, but most of the examples displayed code with .off()
or unbinding happening inside the .on()
/binding.
IMPORTANT NOTE: I am using backbone.js. It is a 'one-page site'. The objects are basically views and their instantiation occurs in the router.
Upvotes: 2
Views: 605
Reputation: 35807
In short, no, there's no meaningful performance penalty to using off
. Now I won't swear on a stack of bibles that it's impossible for off
to cause a performance issue, but I will say that in 99 out of 100 (maybe more like 999 in 1,000 or 9999 in 10,000) real world cases you will never have to worry about off 'causing a performance problem.
To put it another way, off
won't ever cause a noticeable performance slow-down unless you do something really crazy with it, or have a really crazy site that inadvertently does something really crazy with it.
NOT calling off
on the other hand can cause lots of issues, performance-related and otherwise.
Upvotes: 1