nemrrached
nemrrached

Reputation: 99

meteor with jquery events runs only once

I'm using meteor 1.3 and i had to to integrate a "web template" into my meteor application,this "web template" has a custom.js file witch contains j query events, but after integrating the "web template", those events inside js file runs only once, is there a way to fix this, this js file contains a lot of lines and it would be very complicated to move events into my "meteor templates events". Thanks

Upvotes: 0

Views: 75

Answers (1)

JotaBe
JotaBe

Reputation: 39015

The problem is that the events are bount directly to DOM elements inside your template, and when meteor changes the DOM elements, the binding is lost.

What you have to do is to use delegated events, which is done by using jquery .on().

What you have to do is to handle the events in a fixed DOM element, your "changing HTML" parent. When an event happens inside this element, the event "bubbles" up to the fixed DOM element, which handles it. The event carries information about the DOM element that started it, so the on subscription can invoke the right handler.

Note that $('#fixedElement').on(event, selector, handler) specifies:

  • the fixed element which will "catch" the bubbled events
  • the event that you want to handle
  • a selector which filters the descendant elements of the fixed element
  • the handler to execute

So, you can specify which event to handle on which element, with which handler. And this will work event after meteor modifies the DOM.

For example, if you have this:

$('#btnOk').click(function() { alert('Clicked OK!`); });

You have to change it into this:

$('#container').on('click', '#btnOk', function() { alert('Clicked OK!`); });

so that, whenever a DOM element with the Id '#btnOk' which is inside '#cotnainer', the handler will be executed, regardless of the object existign before hand or being created on the fly.

Of course, you must ensure that the #container element exists, and it's not replaced with any other thing. To do so, perhaps you'll have to traverse the DOM tree, for example using jQuery .parent().

Upvotes: 1

Related Questions