2014-03-26 43 views
0

呼叫事件我有以下代碼重複一些時間,只有一些變化:與功能處理器+參數的jQuery

$('#mapContainer').on({ 
    mouseenter: function() { 
     Map.ApplyEvents.Country(this.id); 
    }, 
    click: function() { 
     Map.Zoom.State(this.id); 
    } 
}, 
'.mapaCountry path'); 

// this is in another function 
$('#mapContainer').on({ 
    mouseenter: function() { 
     Map.ApplyEvents.State(this.id); 
    }, 
    click: function() { 
     Map.Zoom.County(this.id); 
    } 
}, 
'.mapaState path'); 

在所有的事件,我得叫一個匿名函數只是調用1功能在裏面。

有沒有辦法擠進這個代碼所需功能分配處理程序,還通知參數與this.id

我要實現的是這樣的:
(注:我知道這是錯誤的語法。)

$('#mapContainer').on({ 
    mouseenter: Map.ApplyEvents.Country(this.id), 
    click: Map.Zoom.State(this.id) 
}, 
'.mapaCountry path'); 

$('#mapContainer').on({ 
    mouseenter: Map.ApplyEvents.State(this.id); 
    click: Map.Zoom.County(this.id) 
}, 
'.mapaState path'); 

回答

0

我知道我以前一直懊惱與此有關。如果我沒有記錯,這是一個聲明的問題。

我認爲這是行不通的。

function myFunction(){} 

這是的。

var myFunction() = function(){} 

也許這並不能解決你確切的問題,因爲我不知道你的函數是如何聲明的。

2

恕我直言,你的第一個片段是爲了實現你想要的最慣用的方式。


如果真有這樣的綁定不計其數,而你的地圖API由採取恰好一個唯一的字符串參數的功能完全,你能拿出一個定製粘合劑:

$.fn.bindIDlistener = function(handlers, sel) { 
    var wrapper = {}, evt; 
    for (evt in handlers) { 
     wrapper[evt] = function(){ handlers[evt](this.id); }; 
    } 
    this.on(wrapper, sel); 
} 

//usage : 
$('#mapContainer').bindIDlistener({ 
    mouseenter: Map.ApplyEvents.Country, 
    click: Map.Zoom.State 
}, 
'.mapaCountry path'); 

$('#mapContainer').bindIDlistener({ 
    mouseenter: Map.ApplyEvents.State, 
    click: Map.Zoom.County 
}, 
'.mapaState path'); 

但我仍然建議強烈思考此方法的小優點(每個事件處理程序20個字符),以應對可能遇到的快速限制(在鏈中添加另一個失敗點,代碼對外部方不太易讀,難以通過處理程序的第二個參數,等等......)