Search code examples
classcountmootoolsfactoryinstances

Control number of objects created in MooTools


Is there a way to count the number of objects created and destroyed in mootools?

Suppose this case:

var Animal = new Class({ 
    initialize: function(){},
    create: function() {
        alert('created!');
    },
    destroy: function() {
        alert('destroyed');
    }
});

var AnimalFactory = new Class({
    initialize: function() {
        for(i=0;i<10;i++) {
            this.add(new Animal());
        }
    },
    add: function(animal) {
        this.animalsContainer.push(animal);
    },
    delete: function(animal) {
        this.animalsContainer.remove(animal);
    }
});

var animalFactory = new AnimalFactory();

I know how many animals I have created at the beginning but, imagine that somewhere in the code the animal destroy function from a concrete animal instance is called (code not shown here). how can i make the animalContainer array update correctly with one less?

Any help will be much appreciated.

Thanks!!


Solution

  • You can use the Events Class as a mix-in so that it notifies the factory of the animal's demise...

    var Animal = new Class({
    
        Implements: [Events,Options], // mixin
    
        initialize: function(options){
            this.setOptions(options);
        },
        create: function() {
            alert('created!');
            this.fireEvent("create");
        },
        destroy: function() {
            alert('destroyed');
            this.fireEvent("destroy", this); // notify the instance
        }
    });
    
    var AnimalFactory = new Class({
        animalsContainer: [],
        initialize: function() {
            var self = this;
            for(i=0;i<10;i++) {
                this.add(new Animal({
                    onDestroy: this.deleteA.bind(this)
                }));
            }
        },
        add: function(animal) {
            this.animalsContainer.push(animal);
        },
        deleteA: function(animal) {
            this.animalsContainer[this.animalsContainer.indexOf(animal)] = null;
            animal = null; // gc
        }
    });
    
    
    var foo = new AnimalFactory();
    console.log(foo.animalsContainer[0]);
    foo.animalsContainer[0].destroy();
    console.log(foo.animalsContainer[0]);
    

    watch it run: http://jsfiddle.net/dimitar/57SRR/

    this is trying to keep the indexes/length of the array intact in case you save them