Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

destroy a function in javascript (jquery)

Is there anyone who knows how to destroy a javascript (jquery) function? I'm using jquery "selectable" and a function call "edit" is fired on selectable "stop" event.

Inside this "edit" function I have nested switch functions with a lot of "click" events and I have many functions within each "click" event. My problem is, every time I fire the "selectable" functions and events inside the function "edit" is fired again but the previous functions and events still exist. What i do now is to unbind every event in the function "edit" on selectable "start" even.

Is this a memory leak problem? and is there a way to "destroy" functions in javascript? i have tried to declare the function to null when the function ends but this does not work. functions and events inside it still exist.

anyone have a clue?

demo page here --> http://dreamerscorp.com/test/test01/javascript_destory_test.html

edit 2009/10/31 :) thanks a lot for your helps, your comments are very useful to me, thanks again!!!

like image 278
ben Avatar asked Oct 30 '09 04:10

ben


2 Answers

You can try to nullify the function, or override it assigning an anonymous function that does nothing:

myFunction = null;
// or 
myFunction = function () {};

You can also do it within the function itself:

var autoDestroy = function () {
  autoDestroy = null;
  //...
  return 1;
};

autoDestroy(); // returns 1
autoDestroy(); // TypeError: autoDestroy is not a function
like image 140
Christian C. Salvadó Avatar answered Oct 06 '22 04:10

Christian C. Salvadó


to unbind events in jquery use unbind function http://docs.jquery.com/Events/unbind

$("something").click(function() {
    $("anotherOne").click(function() {
         ....
    });
});

in this example, every time "something" is clicked, an event handler is added to "anotherOne", so if you click three times, you'll get three event handlers.

$("something").click(function() {
    $("anotherOne").unbind('click').click(function() {
         ....
    });
});

here you're guaranteed to have only one click handler on "anotherOne".

There's no need to destroy previous handler explicitly.

like image 27
user187291 Avatar answered Oct 06 '22 04:10

user187291