Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger a custom event with Meteor js

Tags:

events

meteor

Is it possible to trigger a custom event with Meteor? I see that triggering custom jquery events doesn't work, since the Meteor events are separate from jQuery (as discussed here).

So if I had something like:

Template.foo.events({
    'mouseenter .box, makeSelected .box': function() { ... }
})

It'd be nice if I could do something along the lines of:

Meteor.trigger($('.box')[0], 'makeSelected')

My current workaround is to just store the id that I want as data-id="{{_id}}" on the dom element and then use that to modify a key in the Session, but being able to trigger the event feels more "DRY".

like image 837
MrColes Avatar asked Jan 04 '13 07:01

MrColes


People also ask

Can JavaScript trigger events?

This action can be accomplished through JavaScript event handlers. In addition to JavaScript, jQuery which is equivalent to JavaScript in terms of functionality can also be used to trigger events in a HTML document. In order to work on JavaScript trigger events, it is important to know what is an event.

How do you dispatch custom events in react?

We can create custom events using the Event constructor. We can now finally create our non-existent “ onDialogClose ” event as such: //First, we initialize our event const event = new Event('onDialogClose'); // Next, we dispatch the event. elem.

Can we create custom events?

Creating a Custom Event: To create a custom event we use the Event constructor or CustomEvent interface. The Event constructor creates an Event and CustomEvent creates an Event with more functionality. The below steps are followed in order to create one using a new Event. We create an event using the Event constructor.


2 Answers

Meteor doesn't seem to support custom events at the moment, but you can always just use jQuery (or whatever you want) to create custom events, and then make sure they're re-attached to their respective elements with the rendered event on Templates:

Template.foo.rendered = function() {
  attachEvents();
}
like image 117
Rahul Avatar answered Nov 15 '22 09:11

Rahul


Apparently this now works using jQuery event triggering and standard Meteor event listening syntax. Looking at the code for the Bootstrap carousel, it emits a custom jQuery event by doing the following:

var slideEvent = $.Event('slide.bs.carousel', {
    // event state
})
this.$element.trigger(slideEvent)

I sucessfully listened to this event by doing:

Template.carousel.events({
    'slide.bs.carousel': function (event, template) {
        // event handler code here...
    }
});

I was pleasantly surprised at how easily the Bootstrap (jQuery) events meshed with Meteor.

like image 22
Donuts Avatar answered Nov 15 '22 09:11

Donuts