2011-12-30 3 views
1

mootools에서 생성 및 삭제 된 개체의 수를 계산할 수있는 방법이 있습니까?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 배열을 올바르게 업데이트 할 수 있습니까?

도움이 될 것입니다.

감사합니다. 이 동물의 죽음의 공장을 통지하도록

답변

0

당신은

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

이 실행보고 ... 혼합-에서와 같이 Events 클래스를 사용할 수 있습니다 :이은을 유지하기 위해 노력하고있다 http://jsfiddle.net/dimitar/57SRR/

배열의 인덱스/길이를 그대로 보존하십시오.

+0

안녕하세요, 대단한 답변입니다! fireEvent에 대해 알고 있었지만 그 줄은 this.fireEvent ("destroy", this); // 인스턴스에 알립니다. 및 this.add (새 동물 ({ onDestroy : this.deleteA.bind (this) }))); 이 나를위한 열쇠였습니다. 감사합니다. –