23890123890
23890123890

Reputation: 147

New event type in JavaScript

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?

Upvotes: 2

Views: 887

Answers (1)

josh3736
josh3736

Reputation: 144922

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();

Upvotes: 3

Related Questions