2012-11-07 91 views
0

Possible Duplicate:
setTimeout() inside JavaScript Class using 「this」自定義事件與原型

我發現就如何落實在JavaScript與原型自定義事件這個有趣的文章:http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/

但我對如何實現這個有點卡住,我有這個簡單每隔一段時間觸發一個函數的應用程序。

function App() { 
    window.test = 'test'; 

    this.loginTimer = setInterval(this.checkLogin, 1000); 

    EventTarget.call(this); 
} 
App.prototype = new EventTarget(); 
App.prototype.constructor = App; 

App.prototype.checkLogin = function() { 
    this.fire('test'); 
} 

但這扔我一個錯誤:

Uncaught TypeError: Object [object Window] has no method 'fire'

在文章中描述的,我用同樣的方法,是有什麼我失蹤?

+0

在區間的'checkLogin'功能是不是叫*月*您的應用程序,使用'的setInterval(this.checkLogin.bind(本),...' – Bergi

+0

順便說一句:我不認爲你真的希望所有你的應用只能從一個普通的'EventTarget'實例繼承 - 如果你的應用應該是一個單身人士,創建它爲一個。 – Bergi

+0

我的應用只用了一次,它服務更多作爲一個全球性的東西,我可以跟蹤變量和呼叫雖然你的解決方案似乎有效,但我不確定它是否真的在調用任何東西。我剛開始使用Prototype,所以有可能我還沒有清楚地理解它:http://pastebin.com/YdaY6tjF –

回答

0
var app; 
function createApp() { 
    if (app) return app; // singleton - always the same instance 
    app = new EventTarget(); // basically being the EventTarget object 
    // and extending it with additional properties (as following) 
    // you also could make the EventTarget a property of a plain app object 
    app.checkLogin = function() { 
     this.fire('test'); // this === app if invoked as a method 
    } 
    app.loginTimer = setInterval(function() { 
     app.checkLogin(); // call the method *on* the app 
    }, 1000); 
    return app; 
} 

var player; 
function createPlayer() { 
    if (player) return player; // again, singleton pattern 
    player = {}; 
    player.play = function() { 
     console.log('event tester'); 
    }; 
    // get the app singleton (or create it if not existing) 
    // and add the listener to it 
    createApp().addListener('test', function() { 
     player.play(); // call the method 
    }); 
} 

// usage: 
createApp(); 
createPlayer(); 
// starts logging "event tester" 
+0

謝謝,我沒有使用你的代碼,但仍然使用我的原型方法。 我只是將App實例傳遞給我的播放器並將事件綁定到該事件,現在工作正常。 –