2

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
23890123890
  • 147
  • 1
  • 1
  • 6

1 Answers1

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