Pjottur
Pjottur

Reputation: 622

Event handler on jQuery object

I am trying to bind custom events to a jQuery object, but they will not fire.

Example:

environment = new function(){
this.events = $();
};

environment.events.on('preloader_done', function(){
    console.log('environment event handler');
});

environment.events.trigger('preloader_done');

$(document).on('preloader_done', function(){
    console.log('document event handler');
});

$(document).trigger('preloader_done');

In the example above, only the event bound to the document fires. See jsfiddle: https://jsfiddle.net/ymhp5c8k/

I cannot find any information to tell me why this won't work.

I know that I can create a JavaScript object and then bind the event through jQuery like so:

environment = new function(){
    this.jsobject = {};
};

$(environment.jsobject).on('preloader_done', function(){
    console.log('jsobject event handler');
});

$(environment.jsobject).trigger('preloader_done');

But I would like to know if anyone has an explanation for how I could just set it up as a jQuery object and then call it directly without having to wrap it in jQuery every time.

Upvotes: 2

Views: 61

Answers (1)

afgomez
afgomez

Reputation: 553

You just need to create a jQuery object in your constructor

environment = new function(){
    this.events = $({}); // Here
};

environment.events.on('preloader_done', function(){
    console.log('environment event handler');
});

environment.events.trigger('preloader_done');

That should do the trick.

Upvotes: 3

Related Questions