简体   繁体   English

当在对象内部调用函数时,JavaScript会监听

[英]JavaScript listen for when a function is called inside an object

I have a function which returns a promise that resolves to an object. 我有一个函数,它返回一个可解析为对象的promise。

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. 我可以想到的用真实代码完成此操作的唯一方法是使用内部setInterval方法触发时调用的函数来原型化可解决的对象。

However I was hoping to do this without needing to use prototype in order to streamline the functions API. 但是我希望这样做,而不必使用原型来简化功能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. 这个想法是创建一个包含伪函数的对象,然后在promise解析后更改该函数。 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. 我了解这似乎不是最好的解决方案,但这是我在使用香草javascript时可以想到的唯一方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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