我有JavaScript脚本/库,它几乎工作得很好,除了我似乎不能理解如何添加一个remove方法。例如,你可以这样做(添加的jQuery变得更清晰,更容易理解示例,但我的脚本不需要jQuery):
//Adds a "widget" to the memory
Core.extend('widget',function(m){
$(window).click(function(){ alert(m); });
});
//Actually loads widget, and will alert "hello world" each click on the body
Core.load('widget', 'hello world');
//*SHOULD* make it so that when I click on the window the alert no longer shows
Core.remove('widget');下面是我正在编写的代码
var Core = function(){
var debug = function(m){
console.log(m);
}
var errors = false;
var extensions = {};
var listeners = {};
var extend = function(name,func){
name = name || '';
func = func || function(){};
if(typeof extensions[name] == 'undefined'){
extensions[name] = func;
}
else{
if(errors){
throw new Error('Core extend() error: the extension "'+name+'" already exists');
}
}
}
var load = function(name,params){
name = name || '';
params = params || '';
if(typeof extensions[name] !== 'undefined'){
extensions[name](params);
}
else{
if(errors){
throw new Error('Core load() error: the extension "'+name+'" doesn\'t exist');
}
}
}
//Sends out a notification to every listener set with this name
var push = function(name, value){
name = name || '';
value = value || '';
if(typeof listeners[name] !== 'undefined'){
listeners[name].call(this,value);
}
else{
if(errors){
throw new Error('Core push() error: the extension "'+name+'" doesn\'t exist');
}
}
}
//Saves a function to the listeners object to be called by push()
var listen = function(name, callback){
name = name || '';
callback = callback || function(){};
listeners[name] = callback;
}
//Removes an extension from being called
var remove = function(name){
name = name || '';
if(typeof extensions[name] !== 'undefined'){
delete extensions[name];
}
else{
if(errors){
throw new Error('Core remove() error: the extension "'+name+'" doesn\'t exist');
}
}
}
return {
extend:extend,
load:load,
remove:remove,
push:push,
listen:listen
}
}();示例用例:
http://jsbin.com/enopup
发布于 2011-08-06 16:44:05
您的问题是将函数从核心中移除,但没有解除onClick调用的绑定。我怀疑这是在浏览器中缓存的。您可以通过在remove调用后添加$(Window).unbind(‘’click‘)来快速确认这一点。
JS超出了我的能力范围,但我推荐的可能是一种描述器方法,用于解除可能采取的任何此类操作的绑定。
发布于 2011-08-06 16:44:30
在您的示例中,小部件实际上为click事件附加了一个事件处理程序。
从库对象中移除你的小部件是不够的,因为你附加了一个事件侦听器,你必须移除它。
Unbind
使用jQuery,您可以使用.unbind()方法移除附加到特定元素的每个事件处理程序。
这样,当您再次单击时,它将不会执行任何操作。
https://stackoverflow.com/questions/6965625
复制相似问题