2017-09-05 34 views
0
func parent(children){ 
    for(var i =0;i<children.length;i++){ 
     this.children[i] = new Child(fname, lname); 
    } 
this.printNames = function(){ 
      for(var i =0;i<this.children.length;i++){ 
     console.log(this.children[i].fname); 
    } 
    } 
} 
func child(fname,lname){ 
this.fname = fname; 
this.lname = lname; 
this.changefname = function(_fname){ 
this.fname = _fname; 
this.emit('NameChanged'); 
} 
} 

我怎麼做這樣的事情,怎麼聽在子類中發出的事件對象

parentObj.children.on("NameChanged", parentObj.printNames); 

我要聽由孩子的OBJ在孩子收集發出的事件並調用一個函數父對象。

+0

您要爲數組索引做到這一點,對象權利的價值轉換爲事件對象的事件監聽行動? – turmuka

+0

嗯..我想。你是說這樣的, parentObj.children [i] .on(「NameChanged」,parentObj.printNames); ?如果是這樣,那麼是的。 –

回答

0

這不是太複雜,當你想要一個對象發出一個事件時,你需要給該對象的值爲events.EventEmitter,當你這樣做時,它不能保存一個字符串或數字,而是一個事件。與工作時

實施例的代碼對象

var events = require('events'); 

var example_emitter = new events.EventEmitter; 

var myObj = {}; 

//Basic index of an object 

myObj['someevent'] = new events.EventEmitter; 

myObj['someevent'].on("somemessage", function(message){ 
    console.log(message); 
}) 

myObj['someevent'].emit("somemessage", "this is some message"); 

//Getting to more low level 

myObj['element'] = {}; 
myObj['element']['secondevent'] = new events.EventEmitter; 

myObj['element']['secondevent'].on("anotherMessage", function(message){ 
    console.log('the length of the message is ' + message.length + ' the message is ' + message); 
}) 

myObj['element']['secondevent'].emit("anotherMessage", 'hello there'); 

下面是用於與陣列工作一些示例代碼。爲了詳細說明上述內容,我給出了someArray的一些值,分別是1,23,當我將這三個索引設置爲for循環中的Event對象時,它們的值被覆蓋,所以它們成爲事件對象,並且當您記錄它們時,它們將不會打印1,2,3但是eventObj,eventObj,eventObj

//Working with arrays 

var someArray[1, 2, 3]; 

for(var i = 0; i < someArray.length; i++){ 
    someArray[i] = new events.EventEmitter;  //changing the values 
    someArray[i].on('printTheIndex', function(){ 
    console.log(someArray[i]); 
    }); 

    someArray[i].emit('printTheIndex'); // the indexes are now event objects, they will not log 1,2,3 but objects of events 
} 

因此,爲了使一個元素一樣,你需要首先創建一個new events.EventEmitter

相關問題