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".
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.
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.
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.
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With