0

I wonder how can I bind several handler functions to same event on a element, for example:

$("#this_element").on("click.action1", function(){
/* first thing to run when click this element */
}).on("click.action2", function(){
/* second thing to run when click this element */
}).on("click.action3", function(){
/* last thing to run when click this element */
})
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Kuan
  • 11,149
  • 23
  • 93
  • 201
  • You're binding handlers to events in different namespaces. Did you really intend to do that? – Barmar Oct 20 '15 at 20:17
  • 1
    http://stackoverflow.com/questions/1491718/jquery-more-than-one-handler-for-same-event – Orest Hera Oct 20 '15 at 20:19
  • @Barmar That is just my guess, I thought when I bind the second one, if I still use same event name string, I will override the existing one. – Kuan Oct 20 '15 at 20:34
  • No, you can have multiple handlers for the same event. They'll all run, as explained in the linked question. – Barmar Oct 20 '15 at 20:35
  • @OrestHera Thanks for this. I wonder do u know how to remove certain handler once I bind several handler to same element? – Kuan Oct 20 '15 at 20:37
  • @Kuan Bind to a named function instead of anonymous function. Then you can use `$("#element").off("click", functionName)` – Barmar Oct 20 '15 at 20:39
  • @Barmar Thanks, but how do you know which function out of all the bind function has been off? – Kuan Oct 20 '15 at 20:44
  • You have to keep track of it yourself to know whether you've turned something off. – Barmar Oct 20 '15 at 20:49

1 Answers1

0

Just combine them all into one function:

$("#this_element").on("click", function() {
    // first thing
    // second thing
    // third thing
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • LOL thanks! The reason I can not do this is because the handling function is conditionally bind to the element, not always three parts together, sometimes I need to bind one of them and remove – Kuan Oct 20 '15 at 20:32
  • Could you update the question to show the real structure of the code, including the conditionals? – Barmar Oct 20 '15 at 20:34
  • The reason I did not put real code there is because I am not sure what code should put there, right now, this is just my thinking of design – Kuan Oct 20 '15 at 20:36
  • Is the conditional really done at the time you bind the handlers, or when the handlers run? – Barmar Oct 20 '15 at 20:38
  • let say there is one case: I have a DIV, initially its mousedown event is generating a print out a string in console. Then I setup up a button which is after clicked, the DIV's mousedown event becomes changing color and print string in console. And when mouseup, the DIV's mousedown event return to only print string – Kuan Oct 20 '15 at 20:43
  • You can use a single function, and it can check a variable to determine whether to change the color. Clicking the button will change the value of the variable. – Barmar Oct 20 '15 at 20:48