문제

Currently, I have a cached variable, $this, on which I'm applying .on to respond to various possible types of behaviour triggers.

$this.on('click','.trigger a',rowTrigger);
$this.on('click','.actions nav a',rowAction);

In the jQuery .on Documentation it doesn't mention if there's a way to combine the above two into a single call. For example, something like this might be nice:

$this.onAny({
    click: [
        {'.trigger a':rowTrigger},
        {'.actions nav a':rowAction}
    ]
});

Is there a way to achieve this kind of statement (e.g. an existing plugin to extend .on)?

UPDATE

Use Case (in the current code, prior to a nice solution):

// Plugin 1:
function addTriggers(){
  $this.find('td:last').append('<span class="trigger"><a href="#"></a></span>');
  return {selector:'.trigger a', event:'click', target: $this, callback: rowTrigger};
}

// Plugin 2:
function addInlineNavigation(){
  $navCode = '...'
  $this.find('td:last').append('<div class="actions">'+$navCode.html()+'</div>');
  return {selector:'.actions nav a', event:'click', target: $this, callback: rowAction};
}
도움이 되었습니까?

해결책

Is there a way to achieve this kind of statement (e.g. an existing plugin to extend .on)?

I'm not aware of one. Would be nearly trivial to write. I'm not seeing much advantage to it, though, compared with chaining:

$this.on('click','.trigger a',rowTrigger)
     .on('click','.actions nav a',rowAction);

But again, the plug-in isn't complicated. Here's an untested rough draft:

jQuery.fn.onAny = function(options) {
    var eventName, eventSpec, eventEntry, selector, i;

    for (eventName in options) {
        eventSpec = options[eventName];
        if (jQuery.isArray(eventSpec)) {
            // Your example, where each event name has an array of objects
            // keyed by selector, where the value is the handler
            for (i = 0; i < eventSpec.length; ++i) {
                eventEntry = eventSpec[i];
                for (selector in eventEntry) {
                    this.on(eventName, selector, eventEntry[selector]);
                }
            }
        }
        else {
            // Assuming just a straight handler here
            this.on(eventName, eventSpec);
        }
    }

    return this;
};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top