Goal : Execute function when function -defined in object- is called
Example:
var obj = {
endUpdate: function(){
... (async stuff from library, cannot modify this code)
}
}
I want to write something like this, to know when endUpdate has been called
obj.on('endUpdate', function(){
// do stuff here when "endUpdate" in above object is called
})
You can create a subscriber function quite easily like so
var obj = {
listeners: {
endUpdate: []
},
on: function(name, callbackFn){
this.listeners[name].push(callbackFn);
},
runListeners: function(name) {
this.listeners[name].forEach((fn) => fn());
},
endUpdate: async function(){
await someStuffFromLib();
this.runListeners('endUpdate');
}
}
Otherwise you can enhance the object and chain async functions as long as you maintain the chain all the way through
var obj = {
endUpdate: function(){
const thisIsAPromise = someStuffFromLib();
return thisIsAPromise;
}
}
const newObj = {
endUpdate: (...args) => obj.endUpdate(...args).then(
(result) => { console.log(result)})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.