2011-08-06 18 views
0

我有JavaScript腳本/庫幾乎工作得很好,除了我似乎無法圍繞如何添加刪除方法。例如你會做這樣的事情(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

回答

0

您的問題是,在去除核心功能,但不解除綁定的onClick調用。 我懷疑這是緩存在瀏覽器中。您可以通過在刪除呼叫後添加$(window).unbind('click')來快速確認此情況。

JS超出了我的意思,但是我建議的可能是一種解除綁定方法來解除可能採取的任何此類操作。

+0

是的,我知道關於unbind和removeEventListener,但我很好奇是否有任何方法或「設計模式」讓我用一個簡單的.remove()方法快速解構方法。 –

0

在您的示例中,您的小部件實際上爲click事件附加了一個事件處理程序。

從您的庫對象中刪除您的小部件是不夠的,因爲您附加了一個事件偵聽器,您必須將其刪除。

Unbind

使用jQuery你可以使用.unbind()方法來除去附着於特定元素的每一個事件處理程序。

這種方式當你再次點擊它不會做任何事情。

+0

是的,我知道unbind和removeEventListener,但我很好奇是否有任何方法或「設計模式」讓我用一個簡單的.remove()方法快速解構方法。 –