【问题标题】:How to create and event handler inside a Singleton class - Javascript如何在 Singleton 类中创建和事件处理程序 - Javascript
【发布时间】:2014-12-07 14:49:26
【问题描述】:

我有下一个代码:

// Singleton
var mySingleton = (function () {
    // Private methods and variables

    function privateMethod(){
        console.log( "I am private" );
    }

    var privateVariable = "Im also private";

   return {
      // Public methods and variables
      hello: function () {
        console.log( "I want to ''fire'' the event 'hello'" );
      }
    };
})();

我想创建自己的事件处理系统。我尝试使用以下代码:

var mySingleton = (function () {

    function privateMethod(){
        console.log( "I am private" );
    }

    var handlers = {};
    mySingleton.prototype.registerHandler = function(event, callback) {
       this.handlers[event] = callback;
    };
    mySingleton.prototype.fire = function(event) {
       this.handlers[event]();
    };

    var privateVariable = "Im also private";

    return {
      hello: function () {
        console.log( "I want to ''fire'' the event 'hello'" );
        fire('hello');
      }
    };

})();

我使用如下:

mySingleton .registerHandler('hello', function () {
    alert('Hi!');
});

但这不起作用...抛出下一个错误:

Cannot read property 'prototype' of undefined

有人可以帮帮我吗?

我当前的错误:

Uncaught TypeError: Cannot set property 'mycustomevent' of undefined
Uncaught TypeError: Cannot read property 'mycustomevent' of undefined

【问题讨论】:

    标签: javascript singleton custom-events


    【解决方案1】:

    您的代码正在尝试对尚不存在的对象的“原型”属性进行分配。反正真的没有意义;只需将这些方法放在您要返回的对象中:

    var mySingleton = (function () {
    
        function privateMethod(){
            console.log( "I am private" );
        }
    
        var handlers = {};
        var privateVariable = "Im also private";
    
        return {
          hello: function () {
            console.log( "I want to ''fire'' the event 'hello'" );
            this.fire('hello');
          },
          registerHandler: function(event, callback) {
            handlers[event] = callback;
          },
          fire: function(event) {
            if(handlers[event]){
               handlers[event]();
            }else{
               console.error("Sorry, there aren't any handlers registered with that name");
            }
          }
        };
    })();
    

    您正在构建为“mySingleton”的对象只是一个普通对象;也就是说,它是 Object 构造函数的一个实例。不涉及新的原型。

    您不需要this 引用来访问“处理程序”映射,因为它在事件处理函数的闭包范围内。然而,代码的排列方式确实在使用.fire() API 时需要this,尽管这也可以通过在匿名包装器中本地声明服务函数来解决。p>

    【讨论】:

    • 您好,感谢您的指正。但是...当我尝试使用它时: mySingleton .registerHandler('mycustomevent', function() { ... });还有 mySingleton.fire('mycustomevent');向我抛出下一个错误: Uncaught TypeError: Cannot set property 'mycustomevent' of undefined Uncaught TypeError: Cannot read property 'mycustomevent' of undefined 你能帮我解决这个问题吗?
    • ¡对不起!我忘了删除“this”引用。它工作得很好。非常感谢:)
    • @MartaFernandez 好的,我很高兴它对你有用!
    • 你认为我应该编写代码来检查火灾事件是否被注册?如果我在出现下一个错误之前使用方法“hello”而不调用 registerHandler:undefined is not a function (MySingleton.fire)
    • 是的,您可以检查并抛出一些有用的异常。这在 JavaScript 库中并不常见,但我认为这样做没有任何问题。我最喜欢的框架通常是那些尽可能提供有用的解释性错误的框架。
    【解决方案2】:

    试试下面的代码

    var singleton = (function(){
        var instance;
        var myObj = function(){
            this.name = "myObj";
            this.eventObj = {};
        };
        var localFn = function(){
            if(!instance){
                instance = new myObj();//singleton, instance created once
            }
            return instance;
        };
      //add 2 functions on myObj
        myObj.prototype.addEvent = function(evName, cb){
            this.eventObj[evName] = cb;
        };
        myObj.prototype.invokeEvent= function(evName){
            this.eventObj[evName]();
        };
        return localFn;
    }());
    
    singleton().addEvent("btnClick", function(){alert("click event invoked")});
    singleton().addEvent("btnClick_1", function(){alert("click event invoked")});
    singleton().invokeEvent("btnClick"); //alert "click event invoked"

    【讨论】:

      猜你喜欢
      • 2013-12-24
      • 2015-01-17
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      • 2019-04-13
      • 1970-01-01
      • 2011-08-09
      • 1970-01-01
      相关资源
      最近更新 更多