JavaScript事件实现到基于Closure的对象

JavaScript事件实现到基于Closure的对象

本文介绍了JavaScript事件实现到基于Closure的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于某些闭包的对象,并且想在这里实现事件方案:

I have a Object based on some closure, and want to implement event scheme here:

var class1 = function(val1)
{
    var val = val1;
//------ want to call a method of Object of class1--------
    var self = this;
    setTimeout(function()
    {
        self.onEvent();

    }, 1000);
//----------------
    return {
        f1: function()
        {
            return val;
        },
        onEvent: function()
        {
            console.log('not implemented yet. Override');
        }
    };
};

var obj1 = class1(5);
console.log(obj1.f1()); //5

obj1.onEvent(); //not implemented yet. Override
obj1.onEvent = function()
{
    console.log('event fired');
}

得到错误,我知道原因,我需要一个解决方案: / p>

got error, and I know the reason, and I need a solution:

5
not implemented yet. Override

/....../app.js:9
        self.onEvent();
             ^
TypeError: Object #<Object> has no method 'onEvent'

这可能是这样与addEventListener方案绑定像这样:

(基于
的想法

var class2 = function()
{
    var _this = this;
    _this.events = {};
    var fireEvent = function(name, args)
    {
        if (!_this.events.hasOwnProperty(name)) return;
        if (!args || !args.length) args = [];
        var evs = _this.events[name];
        var l = evs.length;
        for (var i = 0; i < l; i++)
        {
            evs[i].apply(null, args);
        }
    };
    setTimeout(function()
    {
        fireEvent('testEvent', ['hello'])
    }, 1000);
    return {
        addEventListener: function(name, handler)
        {
            if (_this.events.hasOwnProperty(name))
                _this.events[name].push(handler);
            else
                _this.events[name] = [handler];
        }
    };
};
var obj2 = class2();
obj2.addEventListener('testEvent',
    function(data)
    {
        console.log('event fired: ' + data);
    });

事件已触发:hello

但是,我不喜欢使用addEventListener而是使用.onEvent()方案。

However, I prefer not to use addEventListener but .onEvent() scheme.

有可能吗?也许可以使用call / apply。

Is it possible? Perhaps it is possible using call/apply.

感谢您的建议。

推荐答案

在你的第一个代码块中,你返回一个对象,它不同于 this self

In your first block of code, you are returning an object, which is different from this or self.

您不必在构造函数中返回 this ,但是您应该在返回的目的。如果为要返回的对象创建一个变量,可以在 setTimeout 回调中使用它,如下所示:

You don't necessarily have to return this in your constructors but you should assign your functions on the returned object. If you create a variable for the object you want to return, you can use it in your setTimeout callback like so:

var class1 = function(val1)
{
    var val = val1;

    var obj = {
        f1: function()
        {
            return val;
        },
        onEvent: function()
        {
            console.log('not implemented yet. Override');
        }
    };

    setTimeout(function()
    {
        obj.onEvent();

    }, 1000);

    return obj;
};

对于额外的样式点,你可能想要大写你的构造函数的名称c $ c> new 来实例化它们,以使读者更清楚。)

For extra style points, you might want to capitalize the name of your constructors (and perhaps use new to instantiate them to make things clearer to your readers).

这篇关于JavaScript事件实现到基于Closure的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 05:19