Javascript deconstructor

Is there a way to define a destructor for an object in JavaScript that will be called automatically when the object is dropped?

I create my object like this:

function SomeObject(){ this.test = null; this.method = function(){ alert("Testing Method"); }; this.destroy = function(){ // Destroy stuff here }; } var test = new SomeObject(); 

I can cause destruction when necessary, but when the user leaves the page that I cannot destroy. The reason I need to do this is because I am calling functions in php using ajax which saves session data. I would like it to destroy specific session data when im done with this particular js object.

Any ideas?

+4
source share
3 answers

You cannot use the deconstructor for an object, but you can use window.onbeforeunload or window.onunload to make any adjustments at the last moment.

If you return a line from onbeforeunload , it will offer the user this line as a confirm dialog regarding whether they want to leave. This is useful primarily if you want to offer the user to save their work or some similar action that saves state.

+2
source

You can call this function in window.onunload or window.onbeforeunload events. But keep in mind that this can be caused even when the user moves inside your own application or when the back and forward buttons are used.

+2
source

You can bind to the unload event:

 function SomeObject(){ ... var that = this; $(window).unload(function() { that.destroy(); }); } 

Thus, your destroy method will be called when the user leaves the page.

Without jQuery, you can associate an event with this:

 var event = 'load'; var handler = function() { ... }; if (window.addEventListener) { window.addEventListener(event, handler, false); } else { window.attachEvent('on'+event, handler); } 
+2
source

Source: https://habr.com/ru/post/1369218/


All Articles