6

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".

Community
  • 1
  • 1
MrColes
  • 2,453
  • 1
  • 28
  • 38

4 Answers4

5

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();
}
Rahul
  • 12,181
  • 5
  • 43
  • 64
  • Why is it necessary to call attachEvents in startup? Will it not always be called in .rendered anyways? – Erlend V Apr 29 '13 at 10:38
5

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.

Donuts
  • 1,719
  • 2
  • 11
  • 4
0

Meteor reacts when you trigger events the jQuery way (assuming its installed)

$('.box').mouseenter();
Artur
  • 1,125
  • 11
  • 17
0

Clicking #showOffered sets the #searchFilter to a special value and filters the results (not shown):

<template name="brokerProducts">
            <div class="input-group">
              <input id="searchFilter" type="text" class="filter form-control" placeholder="Search for ..." value="{{filterValue}}">
              <span id="showOffered" class="btn input-group-addon">Show Offered</span>
            </div>
</template>

These events worked for me. Click sets the value and triggers the input event which filters the results (not shown):

Template.brokerProducts.events({
  'input .filter': (event, templateInstance) => {
    templateInstance.filter.set(event.currentTarget.value);
  },
  'click #showOffered': (event, templateInstance) => {
    $('input#searchFilter').val('show:offered').trigger('input');
  }
})
Michael Cole
  • 15,473
  • 7
  • 79
  • 96