在jQuery中使用函数处理程序+参数调用事件

安德烈·菲格雷多(Andre Figueiredo)

我有以下代码重复了几次,只是有所不同:

$('#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');
勒格

恕我直言,您的第一个摘录是实现您想要的东西的最惯用的方法。


如果您确实有成千上万个这样的绑定,并且您的Map 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个字符),以应对可能遇到的快速限制(增加链中的另一个失败点,使外部参与者对代码的可读性较差,难以通过)处理程序的第二个参数,依此类推...)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章