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发出的事件,并调用父Object中的函数。
答案 0 :(得分: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
和2
设置为3
,当我将这三个索引设置为for循环中的事件对象,它们的值被覆盖,因此它们成为事件对象,当您记录它们时,它们将不会打印1
,2
,3
但{{1 }},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
}