我正在尝试创建一个自定义的javascript EventManager类。我采用了Grant Skinner在他的easel.js框架中使用的格式来创建类,并且需要坚持使用它。我真的只是在这一点上迷失了 - 我认为 - 至少从概念上讲 - 我在这里有正确的想法,而且主要是范围问题让我逃避。
我希望有人可以帮我解决这个问题,直到addListener和dispatchEvent正常运行。
[code]
(function(window) {
var EventManager = function() {
this.initialize();
}
var p = EventManager.prototype;
// place properties here
// Constructor
p.initialize = function() {
p.listeners = new Array();
}
// public methods
p.addListener = function(fn, event) {
console.log("p.addListener Hit");
console.log("event: " + event);
console.log("handler function: " + fn);
if(!this.listeners[event]) {
this.listeners[event] = [];
}
if(fn instanceof Function) {
this.listeners[event].push(fn);
}
return this;
}
p.dispatchEvent = function(event, params) {
console.log("Dispatch Event");
// loop through listeners array
for(var index = 0; index < listeners[ev].length; index++) {
// execute matching 'event' - loop through all indices and
// when ev is found, execute
listeners[event][index].apply(window, params);
}
}
p.removeListener = function(event, fn) {
// split array 1 item after our listener
// shorten to remove it
// join the two arrays back together
}
window.EventManager = EventManager;
}(window));
[/code]
[code]
<script>
eventManager = new EventManager();
var FooTest = function() {
this.fire = function() {
//alert("fire");
}
this.fire();
};
function onFire() {
// console.log("FIRED!");
}
var o = new FooTest();
eventManager.addListener.call("fire", onFire );
// eventManager.dispatchEvent.call(o,'fire' );
</script>
[/code]
感谢您的帮助!!!
答案 0 :(得分:3)
以下是固定代码的工作示例:http://jsfiddle.net/JxYca/3/
在大多数情况下,您的代码正在运行,这里和那里只是一些小问题。 IFFE是立即调用的函数表达式(IIFE)。这就是你在整个函数(窗口){}(窗口)中所做的。但是在这种情况下,它绝对没有必要,只会污染代码。在javascript中没有hashtable这样的东西,但是,你可以只使用一个对象而不是它。属性的名称成为键,它们的值现在是哈希表的值。
另外一种与你无关的。这种做好事的方式,但如果你有3个处理程序附加到一个事件,第二个处理程序失败,JavaScript异常,第三个将永远不会被执行。您可能希望快速了解prototype.js如何在此处执行事件:https://github.com/sstephenson/prototype/blob/master/src/prototype/dom/event.js他们的事件是非阻塞的。
答案 1 :(得分:0)