views:

107

answers:

1

I have a jQuery draggable() function and on drag is executing several other functions based on an if. Something like this:

$("div.element").draggable({
    drag: function() {
            if  (a=1){
                function1();
                }
            if  (a=2){
                function2();
                }   
            if  (a=3){
                function3();
                }   
    }
});

There are many variables involved and I am looking to optimize this from the performance perspective point of view. Is it possible to make the draggable "know" what function to perform on drag without doing the if checking each time. Something like on drag do just function2() and function3().

Thank you

+1  A: 

You could use jQuery data to store the appropriate function object right with the draggable elements:

// declare the appropriate function for each element
$("select elements that need function1").data("dragFunction", function() {
  // whatever
});
$("select elements that need function2").data("dragFunction", function() {
  // whatever
});

// and then... just execute whatever function is stored in "dragFunction"
$("div.element").draggable({
  drag: function() { return $(this).data("dragFunction")(); }
});
Tomalak
Not quite sure if it will work in my case but I'll give it a try and let you know
Mircea
@Mircea: Maybe it is not exactly what you need, but on the other hand: I think you are doing premature optimization here. The use case (manually dragging an element with the mouse) is not exactly heavy load. A few unused `if` statements won't slow it down.
Tomalak