1

有没有办法计算在 mootools 中创建和销毁的对象数量?

假设这种情况:

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();

我知道一开始我创建了多少动物,但是,想象一下代码中的某处调用了来自具体动物实例的动物破坏函数(此处未显示代码)。我怎样才能使 animalContainer 数组正确更新少一个?

任何帮助都感激不尽。

谢谢!!

4

1 回答 1

0

您可以使用Events该类作为混合,以便它通知工厂动物的死亡......

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]);

看它运行:http: //jsfiddle.net/dimitar/57SRR/

这是试图保持数组的索引/长度不变,以防您保存它们

于 2011-12-30T12:39:40.430 回答