【问题标题】:Control number of objects created in MooTools控制在 MooTools 中创建的对象数量
【发布时间】:2012-01-30 12:46:23
【问题描述】:

有没有办法计算在 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 数组正确更新少一个?

任何帮助将不胜感激。

谢谢!!

【问题讨论】:

    标签: class count mootools factory instances


    【解决方案1】:

    您可以使用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/

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

    【讨论】:

    • 嘿,这是一个很好的答案!我知道fireEvent,但是那些行:this.fireEvent("destroy", this); // 通知实例和 this.add(new Animal({ onDestroy: this.deleteA.bind(this) }));对我来说是关键。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 2023-03-21
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多