vladimirp
vladimirp

Reputation: 1554

Meteor's Session.set causing issues with JQuery code?

I am using Meteor 0.5.4 I have just encountered a strange issue with Meteor's Session.set().

I want to show a simple modal dialogue when user clicks on a template instance.

I am using Template's event map to set some info into Session when user clicks onto a Template instance.

Template.Orders.events({
'click' : function () {
    Session.set("OrderName", this.name);
}
});

Modal dialogue template then displays the data set in Session:

Template.OrderDialogue.OrderName = function() {
    return Session.get("OrderName");
}

and finally here's my JQuery code

Template.Orders.rendered = function() {
    jQuery('a[rel*=leanModal]').leanModal();
}

When I use Session.set() - as showed above inside Template.orders's click event handler - JQuery plugin doesn't show the modal dialogue on the first click on the template instance but only on second click on that exact instance. It takes two clicks on template instance to get the modal dialogue.

When I remove Session.set() everything is working fine - modal dialogue is shown on first click as it's supposed to work.

Debug output shows that Session value is properly set on the first click.

How can Session.set() interfere with my JQuery plugin?

Upvotes: 2

Views: 447

Answers (1)

TimDog
TimDog

Reputation: 8928

leanModal is showing the HTML content of OrderDialogue before the Meteor engine reactively infuses the new content into it, so the key is to wrap the leanModal click in a setTimeout to ensure the reactivity has happened.

Assuming you have:

<template name="OrderDialogue">
    <div id="overlay_content">
       <h1>{{OrderName}}</h1>
    </div>
</template>

<template name="Orders">
    {{#each order}}
        <a href="#overlay_content" rel="leanModal">{{name}}</a>
    {{/each}}
</template>

And your javascript:

Template.Orders.events({
   'click' : function () {
      Session.set("OrderName", this.name);
   }
});

Template.OrderDialogue.OrderName = function() {
   return Session.get("OrderName");
}

Template.Orders.rendered = function() {
   $("a[rel*=leanModal]").leanModal();
}

Then you have to hack the leanmodal widget with a setTimeout on the click event handler, to give the reactivity a moment to render the OrderName content prior to event bubbling.

Assuming this is the script, wrap the click handler in this script (starting around line 23) like this:

$(this).click(function(e) {
    setTimeout(function() {
        var modal_id = $(this).attr("href");
        ...
    }, 1);
});

Upvotes: 2

Related Questions