user686605
user686605

Reputation:

Same jQuery event, separate function

Say that I have a function that needs to execute on $(document).mousemove(). Then I decide I have another function that needs to execute on the same event. Perhaps these two functions are unrelated, so in the name of modularity, one could have two separate functions listening for $(document).mousemove().

Is this bad form? Are there performance implications?

Upvotes: 7

Views: 454

Answers (3)

vittore
vittore

Reputation: 17579

Of course if you decide to set 1000 functions listening one event i would say something wrong with your design, but for me two funcs are just ok

I would go with namespaced handlers in order to keep maintainability, at least if Saint John designed it in jQuery it worth using in some cases so you do this:

$(elem).bind('mousemove.ns1', funcOne);
$(elem).bind('mousemove.ns2', funcTwo);

this way you are able unbind one by one as well

$(elem).unbind('mousemove.ns1');
$(elem).unbind('mousemove.ns2');

Or even

$(elem).unbind('.ns1');

Upvotes: 0

Nathan Taylor
Nathan Taylor

Reputation: 24606

jQuery will automatically append events to a chain, so there is no problem with having duplicate handler definitions for the same event. If you can combine two handler definitions into one reasonably then there's certainly nothing wrong with that approach, but there's little explicit value in doing so other than, perhaps, readability.

Upvotes: 2

Betard Fooser
Betard Fooser

Reputation: 526

Can you not simply do this? Unless I am misunderstanding your question

$(document).mousemove(function(){
    callOneFunction();
    callTwoFunction();
});

Upvotes: 0

Related Questions