使用Prototype的自定义事件

时间:2012-11-07 10:27:52

标签: javascript prototype

  

可能重复:
  setTimeout() inside JavaScript Class using “this”

我发现这篇有趣的文章介绍了如何使用原型http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/

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

但是这给我一个错误:

  

未捕获的TypeError:对象[对象窗口]没有方法'fire'

我使用了与文章中描述的方法相同的方法,有什么我不知道的吗?

1 个答案:

答案 0 :(得分: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"