user1552480
user1552480

Reputation: 207

mootools destructor

Does mootools have a destructor? I have a static variable which counts the instances of the class.
The problem is when an instance is destroyed i can't update my static variable. Is there anyway for the destructor to be extended so i have the posibility to update that var?

Upvotes: 1

Views: 583

Answers (1)

Dimitar Christoff
Dimitar Christoff

Reputation: 26165

Never seen this done in mootools, normally, you let browsers garbage collect so...

this is by far not an ideal solution - it needs to know the scope of the instance (window, other object etc).

mixin class:

var Destructor = new Class({
    destruct: function(scope) {
        scope = scope || window;
        // find the object name in the scope
        var name = Object.keyOf(scope, this);
        // let someone know
        this.fireEvent && this.fireEvent('destroy');
        // remove instance from parent object
        delete scope[name];
    }
});

you then use it in the class you want:

var a = new Class({

    Implements: [Events, Options, Destructor],

    initialize: function(options) {
        this.setOptions(options);
        this.hai();
    },

    hai: function() {
        console.log('hai');
    }

});

finally, you create an instance of the class with an event bound to onDestroy

var instance = new a({
    onDestroy: function() {
        console.log('goodbye cruel world. time to set affairs in order!');
    }
});


instance.destruct();

instance.hai(); // reference error.

I know it's hacky but it may give you the ability to sensibly destroy classes and do cleanup.

Upvotes: 1

Related Questions