在我自己的对象中实现事件 [英] Implementing events in my own object

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

问题描述

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

  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();
};

函数fireTextChanged(){
_this.dispatchEvent(_this.OnTextChanged);
}
}

使用该事件的代码如下: / p>

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

正如您所看到的......在JS中使用事件的默认方式。
但是我不能让它变得烦人......



目前我的问题是我的对象没有实现addEventListener和dispatchEvent。但是这个函数是从元素中正常实现的......



我可以以某种方式使它们可用,还是我必须为自己实现它们?
我如何实施它们?
我是否必须实施自己的事件处理? (有一个处理程序的内部列表,一个添加 - 和删除 - 处理程序函数,并在我想要触发事件时触发每个处理程序)



问候!

解决方案

addEventListener 函数是元素类。一种方法是使 CustomObject 继承自元素,如下所示:

  CustomObject.prototype = Element.prototype; 

问题是元素类可能有不同浏览器之间的不同实现因此,例如点火事件可能并不容易(参见这篇文章)。 / p>

所以我建议你自己这样做。这并不难,尝试这样的事情:

  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){
/ *这有点棘手,因为你如何识别函数?
如果您传递THE SAME处理程序,这个简单的解决方案应该有效。 * /
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);
}
};
}

现在使用它很简单:

  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 worling...

Currently my problem is that my object does not implement "addEventListener" and "dispatchEvent". But this functions are normaly 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 eventhandling? (having a internal list of handlers, an "add"- and "remove"-handler function, and fire each handler when I want to fire the event)

Greetings!

解决方案

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆