Вопрос

Sorry for my english, I'm french :) I created a Mootools class named "Slider". This class has a "slider_element" attribute, which is a DIV element. The class also has a "destroyer" method. This method destroys the DIV element.

The slider_element is supposed to be a div that contains another DIV with a "remove" CSS classname. When I click on the "remove DIV", I want the "destroyer" method to be called, so that the DIV disappears.

Here is my code below, and it works graphically like I want. My question is : when I destroy the DIV element, I don't need no more my Slider instance (here "mySlider"). But my code destroys the DIV elements, not the slider instance. Do this instance still exist ? I suppose yes. So I searched how to destroy an instance of a class with Mootools, but didn't find ... so I supposed I'm doing something the wrong way, even if my code does what I want graphically. Please help :)

var Slider = new Class({
    initialize: function(slider_element){
        this.slider_element = slider_element;
        this.slider_element.getElements('*[class="remove"]').addEvent('click', this.destroyer.bind(this));
    },
    destroyer: function(){
    this.slider_element.destroy();
    }   
});
var myElement = $('my_slider');
var mySlider = new Slider(myElement);

(in reality, this is a simplified code, so that I don't disturb you with my whole code)

Это было полезно?

Решение

There is no way to explicitly destroy an object in JavaScript. The best you can do is to remove all references to it and hope that your JavaScript implementation reuses the memory.

So in principle you can just overwrite any references (like mySlider in your example) with null. But there can easily be 'implicit' references that you can't control, in closures for instance (as used for events) -- you might be able to help the garbage collector by 'cleaning out' any properties that reference other objects, before throwing it away, but then you have to make sure nothing bad happens if a reference survives somewhere and something tries to use those properties.

For elements, Mootools has the destroy method that goes through a whole DOM subtree and clears out all properties as well as the associated storage of the elements, such as event listeners, before removing it from the DOM.

In your case, as @Dimitar Christoff wrote, if you don't have any external code that calls methods on the Slider object, you don't need to save a reference to it in var mySlider.

And if you don't do that, the only thing that keeps the Slider object alive is the reference from the stack frame of the closure that is built by .bind(this) in the addEvent call. When the event fires and destroy is called, the event listener is removed, and the JavaScript engine is free to deallocate the Slider object as well.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top