Koks Skirtumas
Koks Skirtumas

Reputation: 93

How Do I Handle Template Events When Multiple Template Instances Exist?

I have same template included in 2 places with different parameters like that:

{{> newPost isReply=true replyTo=this}}

When I put breakpoint in helper method I see that this.isReply variable is indeed set to true, hoverer in events function it is false. I think that the reason is that there are several inclusion of same template and another one are where this flag is set to false and selector fits that template too and it is invoked so I get this data context inconsistency between templates. Here is selector example:

'click #savePost' : function() {
      if (this.isReply) {
      ....

My question is maybe someone can explain how exactly meteor works in such situation and how should approach such situation? Right now I think solution would be #savePost unique for each template, but I am interested if the way I am heading is even a good practice in meteor? Also as you understand newPost template contains button #savePost, how I should make it unique? I can't do:

'click #savePost' + someId : function() {

Upvotes: 0

Views: 285

Answers (2)

Conor Strejcek
Conor Strejcek

Reputation: 392

First of all, if I'm understanding this correctly, you have multiple of the same ids on the page at the same time (multiple #savePosts) which is invalid html. Instead, you should make it a class (.savePost).

Regardless, you are allowed to have the same selector in multiple places, and Meteor can differentiate between them. In the event function, you have access to the data context and the target of the event.

For example:

Template.newPost.events({
    'click .savePost': function (event) {
        console.log(this); // this will return the data context
        console.log(this.isReply); // this should give you a correct value
        console.log($(event.target)); // this is how to select the button that was just clicked
        console.log($(event.target).val()); // this will give you the value
    }
});

This should work regardless of how many templates use the same class for a click event.

Upvotes: 0

fardeem
fardeem

Reputation: 594

I think the problem is that you're trying to access the data using this. The right way is to use the Template.instance().data. Example:

'click #savePost': function( e, tmpl ) {

  if ( tmpl.data.isReply )
    //do stuff.

}

Let me know if it works.

Upvotes: 0

Related Questions