Function.prototype.bind = function(context){
var _method = this;
return function(e) {
var array = [e || window.event];
return _method.apply(context, array);
};
};
/**
* Attach event listener to a DOM object
*
* @param domObj
* @param evType, for example "click", "load" etc
* @param thi$, the context of handler
* @param handler, event handler
*/
$attachEvent = function(domObj, evType, thi$, handler){
var _handler = handler.bind(thi$);
if(domObj.addEventListener){
domObj.addEventListener(evType, _handler, false);
}else{
domObj.attachEvent("on"+evType, _handler);
}
return _handler;
};
/**
* Detach event listener from a DOM object
*
* @see J$VM.attachEvent(domObj, evType, thi$, handler)
*/
$detachEvent = function(domObj, evType, thi$, handler){
if(domObj.removeEventListener){
domObj.removeEventListener(evType, handler, false);
}else{
domObj.detachEvent("on"+evType, handler);
}
};
var Button = function(id){
this.div = document.createElement("div");
this.div.id = id;
this.onClick = function(e){
alert(this.div.id); // 这时this是指向Button实例的
// 假设在这个逻辑中我们需要移除事件句柄,但其实这一句也是不如我们预期的。
$detachEvent(this.div, "click", this, this.onClick);
};
$attachEvent(this.div, "click", this, this.onClick);
};
|