這不是太複雜,當你想要一個對象發出一個事件時,你需要給該對象的值爲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循環中的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
您要爲數組索引做到這一點,對象權利的價值轉換爲事件對象的事件監聽行動? – turmuka
嗯..我想。你是說這樣的, parentObj.children [i] .on(「NameChanged」,parentObj.printNames); ?如果是這樣,那麼是的。 –