简体   繁体   中英

JavaScript listen for when a function is called inside an object

I have a function which returns a promise that resolves to an object.

I want this object to have an event I can listen to every time this event is internally called.

Using psudeo code it would look like this:

// function that returns the promise
function myFunction(){
    return new Promise(function(resolve, reject) {
        var obj = {};

        obj.running = event;        // this is a fake line of code
        setInterval(function(){ 
            obj.running             // this should trigger
        }, 3000);                   // something that can be listened to
        resolve(obj);                                    
    });
}

// function that can listen to the event
myFunction().then(function(obj){
    obj.event(){ // Fake event listener
        alert("the set interval function from the code above just ran")
    }
})

The only way I can think to do this with real code would be to prototype the resolved object with a function that is called when the internal setInterval method fires.

However I was hoping to do this without needing to use prototype in order to streamline the functions API. Is there any other method of doing this in real life?

The problem is you're setting the listener after the broadcaster. Ideally, the listener should be created before the broadcaster is created, so that the listener could listen to every broadcast.

Anyways, an approach could be using an outside object as a holder of the event, so that the listener is created first.

var object = {
    running: function(){ } 
};
// function that returns the promise
function myFunction(object){
return new Promise(function(resolve, reject) {
    setInterval(function(){ 
        object.running();        // this should trigger
    }, 3000);                   // something that can be listened to

});
}

// function that can listen to the event
myFunction(object).then(function(response){
    object.running = function() {
      //do stuff here;
    };
});

The idea is to create an object which holds the pseudo function, then change that function once the promise resolves. I understand this feels like not the best solution, but this is the only way I could think of doing it while using vanilla javascript.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM