I'd like to make a new event type in JavaScript. Say I have some criteria for when a user hasAquiredIceCream
, and I'd like to trigger and bind to this event based on the criteria. How could I make a new event in JavaScript? I'm using jQuery, so ideally I'd be able to use it with .trigger('hasAquiredIceCream')
and .bind('hasAquiredIceCream')
. I'm assuming a pure JavaScript solution would work with jQuery just fine (it wouldn't need to be a plugin), can this be done?
Asked
Active
Viewed 881 times
2

Brian Tompsett - 汤莱恩
- 5,753
- 72
- 57
- 129

23890123890
- 147
- 1
- 1
- 6
-
1See similar question http://stackoverflow.com/questions/399867/custom-events-in-jquery and http://api.jquery.com/trigger/. `.trigger()` and `.bind()` support custom events. – Rob Cowie May 27 '11 at 14:11
-
It already works like you described it... – Felix Kling May 27 '11 at 14:27
-
@felix ahh, I wasn't aware I didn't need to define it first before using it – 23890123890 May 27 '11 at 14:55
1 Answers
3
Using jQuery's .trigger()
, you can trigger custom events on any element or on a JavaScript object.
var obj = { id: 0, ... };
$(obj).bind('custom', function(e, arg, ...) { ... });
$(obj).trigger('custom', [arg, ...]);
Or, using plain JavaScript, implement the observer pattern:
function EventHelper() {
this.handlers = [];
this.bind = function(fn) {
this.handlers.push(fn);
};
this.trigger = function(args) {
for (var i = 0; i < this.handlers.length; i++) {
this.handlers[i].call(this, args);
}
};
return this;
}
var event = new EventHelper();
event.bind(function() { ... });
event.trigger();

josh3736
- 139,160
- 33
- 216
- 263