简体   繁体   中英

Call event with function handler + parameter in jQuery

I have the following code that is repeated some times, with only some variation:

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

In all events, I have to call an anonymous function just to call 1 function inside.

Is there a way to squeeze this code assigning handler to desirable functions, but also informing parameter with this.id ?

I want to achieve something like this:
(note: I know that it's wrong syntax.)

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

IMHO, your first snippet is the most idiomatic way to achieve what you want.


If you really have zillions of such bindings, and your Map API consists exclusively of functions taking exactly one single string parameter, you could come up with a custom made binder :

$.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');

but I would still advise to strongly ponder the small benefits (20 chars per event handler) of this approach against the quick limitations you can bump in (add yet another point of failure in the chain, code less readable to external party, difficult to pass a second argument to the handlers, etc...)

I know I've been annoyed with this before. If I remember correctly it's a matter of declaration.

I think this doesn't work.

function myFunction(){}

And this does.

var myFunction() = function(){}

Maybe this doesn't solve your exact problem as I don't know know how your functions are declared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM