1

I have been trying to implement a wildcard name within a custom event handler. A fixed event name is working fine but I would like the handler to handle a number of different scenarios.

// this works fine
this.on("custom_event_name", function(e) {
  //some stuff
));

This also works

// this also works
this.on("event_"+foo, function(e) {
   //some stuff
));

What I have been trying to achieve is something similar to how wildcards work in JQuery selectors

$("[class^=bar]")

Is this possible with event handlers?

Thanks

Toby Risk
  • 25
  • 5

2 Answers2

2

This isn't possible, but you can do something very similar by following the answer here: How to bind to all custom events in jQuery

But there is a different system in place for handling this type of thing that I believe is a much better structure (and more efficient too). What you want to do is pass data to your trigger calls. So you could fire events like this:

a.trigger('custom_event', ['foo']);

Or this:

a.trigger('custom_event', ['bar']);

And then you can just set up one event handler where you test against the passed data:

this.on('custom_event', function(e, type) {
    if (type === 'foo') {
        //...
    } else if (type === 'bar') {
        //...
    }
});

There are other alternatives to handling state besides this (e.g. in the DOM), but putting state in the event names isn't a very viable method.

Community
  • 1
  • 1
Ben Lee
  • 52,489
  • 13
  • 125
  • 145
-1

try it the backwoods way, with regular old event signals:

$('[name^="beginning"]').click(function(){
    alert('You did it!');
});
omikes
  • 8,064
  • 8
  • 37
  • 50