以下是我所拥有的:
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
正确显示两个按钮(" Say World"" Say Town")。但是,如果你点击任何按钮,输出总是" Town" (要创建和渲染的最后一个)。
如何在模板中共享变量,使其对于每个创建的模板都是唯一的?换句话说,我希望能够在创建的事件中为变量设置值,然后能够在事件中访问它们(对于创建/呈现的每个模板)。
答案 0 :(得分:1)
您只需将对象作为上下文传递给hello
模板。尝试用以下代码替换所有代码:
body
div {{> hello name='World' }}
div {{> hello name='Town' }}
template(name="hello")
button.sayHello Say {{name}}
Template.hello.events
'click .sayHello': (e, t) ->
console.log t.data.name
推荐阅读:
答案 1 :(得分:0)
在您的示例中,obj由模板hello的每个实例共享。 尝试使用模板实例作为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