Javascript自定义eventlistener无法正常工作?

时间:2014-12-10 09:35:12

标签: javascript

这些是我的自定义事件侦听器中无法正常工作的代码部分。

为什么当它们相同时返回'-1'var idx=functionList[eventType].indexOf(callback)

当我在myObject.removeCustomEventListenr()方法

中使用以下内容时
console.log(functionList[eventType][0]) /*the console shows 
function(){console.log('firedEvent')*/
console.log(callback) /*the console shows 
function(){console.log('firedEvent')*/

同样的事情,为什么它不起作用

以下是造成问题的完整部分

var myObject = {}
var functionList = {}

myObject.addCustomEventListener = function(eventType,callback){
    if(!functionList[eventType]){
        functionList[eventType] = []
    }
    functionList[eventType].push(callback)
    //creates functionList.start[0] = function(){console.log('firedEvent')}
}

myObject.removeCustomEventListener = function(eventType,callback){
    if(functionList[eventType]){
        var idx = functionList[eventType].indexOf(callback)
        console.log(idx) //logs '-1' should however match and return 0
        if(idx!=-1){
            functionList[eventType].splice(idx,1)
            console.log('removed')//obviously does not remove the function form the array
        }
    }
}

myObject.addCustomEventListener('start',function(){console.log('firedEvent')})
myObject.removeCustomEventListener('start',function(){console.log('firedEvent')})

请解释为什么会发生这种情况以及如何解决这个问题?

由于

1 个答案:

答案 0 :(得分:0)

问题是你将2个不同功能的引用传递给addremove函数,这里:

myObject.addCustomEventListener('start',function(){console.log('firedEvent')})
myObject.removeCustomEventListener('start',function(){console.log('firedEvent')})

虽然函数中的代码是相同的,但就JavaScript而言,它们都是单独的对象,这意味着在将另一个传递给indexOf()时无法找到它们

这应该有效:

var callback = function(){
    console.log('firedEvent')
};
myObject.addCustomEventListener('start', callback)
myObject.removeCustomEventListener('start', callback)

var myObject = {}
var functionList = {}

myObject.addCustomEventListener = function(eventType,callback){
    if(!functionList[eventType]){
        functionList[eventType] = []
    }
    functionList[eventType].push(callback)
    //creates functionList.start[0] = function(){console.log('firedEvent')}
}

myObject.removeCustomEventListener = function(eventType,callback){
    if(functionList[eventType]){
        var idx = functionList[eventType].indexOf(callback)
        console.log(idx) //logs '-1' should however match and return 0
        if(idx!=-1){
            functionList[eventType].splice(idx,1)
            alert('removed')//obviously does not remove the function form the array
        }
    }
}
var callback = function(){
    console.log('firedEvent')
};
myObject.addCustomEventListener('start', callback);
myObject.removeCustomEventListener('start', callback);