我正在嘗試向我的作用域添加事件處理程序。功能addEvent
工作正常。但是,如果我通過一個函數來處理程序是這樣的:如何傳遞封閉範圍中的事件處理程序
this.addEvent(window, "resize", self.resizeAd(this));
的功能將不會被傳遞給事件(The eventHandle is undefinded)
,我不知道爲什麼。
這裏是我的代碼:
(function(window, document, undefined) {
'use strict';
var adTech = window.adTech = {
get: function() {
return _instance;
},
//Main entry point.
init: function(options) {
return _instance || new ADTECH(options);
}
};
var ADTECH = function(options) {
var defaultOptions = {
adID : '5202402',
hiddenClassName : 'hidden'
};
this.options = this.extend(options, defaultOptions);
this.makeAd();
_instance = this;
return _instance;
}
ADTECH.prototype = {
extend: function(source, target) {
if (source == null) { return target; }
for (var k in source) {
if(source[k] != null && target[k] !== source[k]) {
target[k] = source[k];
}
}
return target;
},
log: function(msg){
if(window.console){
console.log(msg);
}
},
debounce: function(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
},
addEvent: function (elem, type, eventHandle) {
console.log("adEvent is undefined: ",eventHandle);
if (elem == null || typeof(elem) == 'undefined') return;
if (elem.addEventListener) {
elem.addEventListener(type, eventHandle, false);
} else if (elem.attachEvent) {
elem.attachEvent("on" + type, eventHandle);
} else {
elem["on" + type] = eventHandle;
}
},
// Function to resize div ad to take the full space we need/get
resizeAd : function(this){
this.log("resizeAd done.");
var ad = document.getElementById(this.options.adID);
this.log(ad);
// do not work
// this.debounce(function() {
// console.log("tat:");
// }, 250)
},
// insert ad
makeAd: function() {
this.addEvent(window, "resize", this.resizeAd(this));
var self = this;
//also do not work
this.addEvent(window, "resize", self.resizeAd(this));
}
}
// Singleton
var _instance;
}(window, document));
var API = adTech.init();
'this.resizeAd(this)'是一個**函數調用** - 你沒有傳遞函數,你傳遞調用函數的結果。 – Pointy
好吧我把它推到this.addEvent(窗口,「resize」,this.resizeAd); 但現在我沒有進一步訪問此(例如this.log) – hamburger