2013-02-22 104 views
0

當我試圖傳遞參數的的addEventListener它的行爲異常傳遞參數回調

var animateFunction = function (i) { 
if (animBool) { 
    Fn.slideData(values(i)); // To fetch some data 
    util.animate.tweenAnimate(sliderWrapper, 0 , Math.ceil("-"+sliderWidth)); 
    animBool = 0; 
} else { 
    util.animate.tweenAnimate(sliderWrapper, Math.ceil("-"+sliderWidth) ,0); 
    animBool = 1; 
} 
}; 

for (i = 0; i < annotateArray.length; i++) { 
//To Remember the state of value "i" 
(function (i) { 
    //Custom Event Listener for fallback for IE 
    util.addEvent(annotateArray[i], "click", animateFunction(i), true); 
}(i)); 
} 

for (i = 0; i < annotateArray.length; i++) { 

    //Custom Remove Event Listener for fallback for IE 
    util.removeEvent(annotateArray[i], "click", animateFunction); 

} 

//Custom Bind Event Method 
util.addEvent = function (obj, evt, callback, capture) { 
    if (window.attachEvent) { 
     obj.attachEvent("on" + evt, callback); 
    } else { 
     if (!capture) { 
      capture = false; 
     } 
     obj.addEventListener(evt, callback, capture); 
    } 
}; 

我試圖動態綁定事件,所有的元素,但聞一點擊功能沒有按」的元素t表現如預期

回答

1

你實際上將undefined作爲事件處理程序傳遞,而不是實際的回調。這裏:

util.addEvent(annotateArray[i], "click", animateFunction(i), true); 

您正在調用函數,該函數返回undefined。您必須將函數引用傳遞給addEventListener。你已經有了一些東西「在循環中記住'我'的價值狀態,但是你沒有正確使用它。它應該是:

for (i = 0; i < annotateArray.length; i++) { 
    //To Remember the state of value "i" 
    (function (i) { 
     // Custom Event Listener for fallback for IE 
     util.addEvent(annotateArray[i], "click", function() {animateFunction(i)}, true); 
    }(i)); 
} 
+0

嗯,但我需要解綁事件太......我經過參考回調函數的原因... u能檢查這塊編輯代碼 – 2013-02-22 15:13:23

+0

然後你就可以創建一個數組並存儲對所有處理程序的引用(如'function(){animateFunction(i)}')。您可以稍後使用數組中的引用來解除綁定。 – bfavaretto 2013-02-22 17:52:23

+0

謝謝隊友:)終於必須創建一個數組並存儲對所有處理程序的引用 – 2013-02-27 20:06:54