Rinux
Rinux

Reputation: 895

Unable to load Meteor template, set context and bind events

I am trying to render and append a template (ticket_edit) to the body. I need to set a context to the newly appended template, and the events of ticket_edit should be bound to that template.

The code:

Template.ticket.events = {
    'click a.edit' : function (event) {
        //when the edit button has been clicked, load template 'ticket_edit' 
        //with the current context. Please see situation 1 and 2.
    }   
}

Template.ticket_edit.events = {
     'click a.save' : function (event) {
        //this won't do anything when i have supplied a context!
    }
}

So the problem is:

-I can set the context, but then the events are not bound to the newly added template.

-If I don't set the context the events are bound properly.

But i need both the events and the context.

Situation 1:

'click a.edit' : function (event) {
    //applying a context to the template will result in events not being bound.
    $('body').append(Meteor.render(Template.ticket_edit(this)));
}

Sitation 2:

'click a.edit' : function (event) {
    //this way, the events will execute properly and i can save my ticket. 
    //However, no context is supplied!
    $('body').append(Meteor.render(Template.ticket_edit));

}

Does anybody have a good method for doing this? I'm fairly new to Meteor, so maybe you have a better method of dynamically loading templates.

Upvotes: 0

Views: 149

Answers (1)

sbking
sbking

Reputation: 7680

Don't use jQuery for this, just do it directly with the template and a #with block. Something like this:

<body>
  {{> tickets}}
</body>

<template name="tickets">
  {{#each tickets}}
    {{> ticket}}
  {{/each}}

  {{#with currentTicket}}
    {{> editTicket}}
  {{/with}}
</template>

Template.tickets.tickets = function() {
  return Tickets.find();
};

Template.tickets.currentTicket = function () {
  return Tickets.findOne({ _id: Session.get( "currentTicket" ) });
};

Template.ticket.events({
  'click a.edit' : function () {
    Session.set( "currentTicket", this._id );
  }
});

Because we're using a #with block, the editTicket template won't get rendered until you click the edit button (setting the "currentTicket" in the Session).

It's also possible to just do this (no #with block):

{{> editTicket currentTicket}}

But that causes editTicket to always be rendered, just without any context until the Session var gets set.

Note that because we're using Session, the user won't be interrupted by reloads/hot code pushes.

Upvotes: 2

Related Questions