簡體   English   中英

當在對象內部調用函數時,JavaScript會監聽

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

我有一個函數,它返回一個可解析為對象的promise。

我希望此對象有一個事件,每次在內部調用此事件時,我都可以收聽。

使用偽代碼,它看起來像這樣:

// 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")
    }
})

我可以想到的用真實代碼完成此操作的唯一方法是使用內部setInterval方法觸發時調用的函數來原型化可解決的對象。

但是我希望這樣做,而不必使用原型來簡化功能API。 現實生活中還有其他方法嗎?

問題是您要在廣播員之后設置監聽器。 理想情況下,應該在創建廣播者之前創建偵聽器,以便偵聽器可以收聽每個廣播。

無論如何,一種方法可能是使用外部對象作為事件的持有者,以便首先創建偵聽器。

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;
    };
});

這個想法是創建一個包含偽函數的對象,然后在promise解析后更改該函數。 我了解這似乎不是最好的解決方案,但這是我在使用香草javascript時可以想到的唯一方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM