Dom*_*fer 9 javascript javascript-events
我想要的是一个提供一些事件的自定义对象.例如:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
使用该事件的代码如下所示:
myCustomObject = new CustomObject();
myCustomObject.addEventListener(CustomObjectTextChangedEventName, handleTextChanged, false);
Run Code Online (Sandbox Code Playgroud)
正如您所看到的......在JS中使用事件的默认方式.但我不能让它变得烦人......
目前我的问题是我的对象没有实现"addEventListener"和"dispatchEvent".但是这个功能是从"元素"正常实现的......
我可以以某种方式提供它们,还是我必须为自己实现它们?我该如何实施它们?我是否必须实施自己的事件处理?(具有处理程序的内部列表,"添加" - 和"删除" - 处理程序功能,并在我要触发事件时触发每个处理程序)
问候!
fre*_*ish 18
该addEventListener函数是一种Element类的方法.一种方法是CustomObject继承Element像这样:
CustomObject.prototype = Element.prototype;
Run Code Online (Sandbox Code Playgroud)
问题是Element类可能在不同的浏览器中有不同的实现.因此,例如射击事件可能并不容易(见本文).
所以我建议你自己做这件事.这并不难,尝试这样的事情:
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);
}
};
}
Run Code Online (Sandbox Code Playgroud)
现在使用它就像:
var co = new CustomObject();
co.addEventListener('textChange', function(name) {
console.log(name);
});
co.fireEvent('textChange', ['test']);
Run Code Online (Sandbox Code Playgroud)
这是一个基本的解决方案.你可能想改变它,但我认为你应该掌握这个想法.
| 归档时间: |
|
| 查看次数: |
5810 次 |
| 最近记录: |