Manuel
Manuel

Reputation: 11469

Use a separate variable for each template created

Here's what I have:

home.jade

body
  div {{> hello 'World' }}
  div {{> hello 'Town' }}

hello.jade

template(name="hello")
  button.sayHello Say {{name}}

hello.coffee

obj = {}
Template.hello.created = ->
  obj.name = this.data

Template.hello.helpers
  name: -> obj.name

Template.hello.events
  'click .sayHello': -> console.log obj.name

It displays the two buttons correctly ("Say World" and "Say Town"). But if you click any button the output is always "Town" (the last one to be created and rendered).

How can I share a variable in a template so that it's unique for each template created? In other words I want to be able to set values on a variable in the created event and then be able to access them in the events (for each template created/rendered).

Upvotes: 0

Views: 60

Answers (2)

David Weldon
David Weldon

Reputation: 64312

You just need to pass an object as the context to the hello template. Try replacing all of your code with:

hello.jade

body
  div {{> hello name='World' }}
  div {{> hello name='Town' }}

template(name="hello")
  button.sayHello Say {{name}}

hello.coffee

Template.hello.events
  'click .sayHello': (e, t) ->
    console.log t.data.name

Recommended reading:

Upvotes: 1

Kuba Wyrobek
Kuba Wyrobek

Reputation: 5273

In your example obj is shared by every instance of template hello. Try to use instance of template as a key in obj:

obj = {}
Template.hello.created = ->
  // this is instance of template
  obj[this] = {name : this.data }


Template.hello.helpers
  // here is problem, there is no access to template instance:
  // see https://github.com/meteor/meteor/issues/1529
  // name: -> obj[this].name

Template.hello.events
  'click .sayHello': (e, tmpl)-> console.log obj[tmpl].name

Upvotes: 0

Related Questions