在自定义对象中实现事件

在自定义对象中实现事件

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

问题描述

我想要的是一个提供一些事件的自定义对象.例如:

  var CustomObjectTextChangedEventName ='textChanged';var CustomObject = function(){var _this = this;var _text =";_this.OnTextChanged = document.createEvent("Event");_this.OnTextChanged.initEvent(CustomObjectTextChangedEventName,true,false);_this.ChangeText =函数(newText){_text = newText;fireTextChanged();};函数fireTextChanged(){_this.dispatchEvent(_this.OnTextChanged);}} 

使用该事件的代码如下:

  myCustomObject = new CustomObject();myCustomObject.addEventListener(CustomObjectTextChangedEventName,handleTextChanged,false); 

如您所见...在JS中使用事件的默认方式,但我无法使其正常工作...

当前,我的问题是我的对象未实现 addEventListener dispatchEvent ,但是此功能通常是从"element"实现的...

我可以以某种方式使它们可用,还是必须自己实现它们?我该如何实施它们?

我必须实现自己的事件处理吗?(具有内部处理程序列表,添加"-和删除"-处理程序功能,并在我要触发事件时触发每个处理程序)?

解决方案

addEventListener 函数是 Element 类的方法.一种方法是使 CustomObject 像这样从 Element 继承:

  CustomObject.prototype = Element.prototype; 

问题在于 Element 类在不同的浏览器之间可能具有不同的实现.因此,例如触发事件可能并不容易(请参见这篇文章)./p>

因此,我建议您自己执行此操作.不难,尝试这样的事情:

  var CustomObject = function(){var _this = this;_this.events = {};_this.addEventListener =函数(名称,处理程序){如果(_this.events.hasOwnProperty(name))_this.events [name] .push(handler);别的_this.events [name] = [handler];};_this.removeEventListener =函数(名称,处理程序){/*这有点棘手,因为您将如何识别功能?如果您传递THE SAME处理程序,则此简单的解决方案应该可以使用.*/如果(!_this.events.hasOwnProperty(name))返回;var index = _this.events [name] .indexOf(handler);如果(索引!= -1)_this.events [name] .splice(index,1);};_this.fireEvent = function(name,args){如果(!_this.events.hasOwnProperty(name))返回;如果(!args ||!args.length)args = [];var evs = _this.events [name],l = evs.length;对于(var i = 0; i< l; i ++){evs [i] .apply(null,args);}};} 

现在使用它非常简单:

  var co = new CustomObject();co.addEventListener('textChange',function(name){console.log(name);});co.fireEvent('textChange',['test'])); 

这是一个基本的解决方案.您可能想要更改它,但我认为您应该掌握这个想法.

What I want to have is a custom object which provides some events.For example:

var CustomObjectTextChangedEventName = 'textChanged';
var CustomObject = function () {
    var _this = this;
    var _text = "";

    _this.OnTextChanged = document.createEvent("Event");
    _this.OnTextChanged.initEvent(CustomObjectTextChangedEventName, true, false);

    _this.ChangeText = function (newText) {
        _text = newText;
        fireTextChanged();
    };

    function fireTextChanged() {
        _this.dispatchEvent(_this.OnTextChanged);
    }
}

The code to use the event would look like:

myCustomObject = new CustomObject();
myCustomObject.addEventListener(CustomObjectTextChangedEventName, handleTextChanged, false);

As you can see... the default way of using events in JS, but I can not make it work...

Currently my problem is that my object does not implement addEventListener and dispatchEvent, but this functions are normally implemented from "element"...

Can I make them available somehow or do I have to implement them for my own?How I have to implement them?

Do I have to implement my own event handling? (having a internal list of handlers, an "add"- and "remove"-handler function, and fire each handler when I want to fire the event)?

解决方案

The addEventListener function is a method of Element class. One way is to make CustomObject inherit from Element like this:

CustomObject.prototype = Element.prototype;

The problem is that Element class may have different implementations among different browsers. So for example firing events may not be easy (see this post).

So I advice doing this by yourself. It is not difficult, try something like this:

var CustomObject = function () {
    var _this = this;
    _this.events = {};

    _this.addEventListener = function(name, handler) {
        if (_this.events.hasOwnProperty(name))
            _this.events[name].push(handler);
        else
            _this.events[name] = [handler];
    };

    _this.removeEventListener = function(name, handler) {
        /* This is a bit tricky, because how would you identify functions?
           This simple solution should work if you pass THE SAME handler. */
        if (!_this.events.hasOwnProperty(name))
            return;

        var index = _this.events[name].indexOf(handler);
        if (index != -1)
            _this.events[name].splice(index, 1);
    };

    _this.fireEvent = function(name, args) {
        if (!_this.events.hasOwnProperty(name))
            return;

        if (!args || !args.length)
            args = [];

        var evs = _this.events[name], l = evs.length;
        for (var i = 0; i < l; i++) {
            evs[i].apply(null, args);
        }
    };
}

Now using it is as simple as:

var co = new CustomObject();
co.addEventListener('textChange', function(name) {
    console.log(name);
});
co.fireEvent('textChange', ['test']);

This is a basic solution. You may want to alter it, but I think you should grasp the idea.

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

08-01 20:38