0

重複の可能性:
「this」を使用したJavaScriptクラス内のsetTimeout()</a>

プロトタイプを使用して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:オブジェクト[オブジェクトウィンドウ]にはメソッド'fire'がありません

記事で説明したのと同じ方法を使用しましたが、何か足りないものがありますか?

4

1 に答える 1

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"
于 2012-11-07T11:19:38.827 に答える