我刚开始使用MeteorJS
如果我有一系列按钮,有没有办法根据我单击的按钮来更改页面的正文?
如果我有一个名为"Hello"的按钮,我希望正文更改为"你好"。
感谢
使用Session
变量
HTML
<body>
{{> main}}
</body>
<template name="main">
<p>{{text}}</p>
{{> button}}
</template>
<template name="button">
<button type="button">Hello</button>
</template>
JS-
Template.main.onCreated(function(){
Session.set("text", "Default");
});
Template.main.helpers({
text: function(){
return Session.get("text");
}
});
Template.button.events({
"click button": function(event, template){
var buttonText = template.$("button").text();
Session.set("text", buttonText);
}
});
使用ReactiveVar
来避免全局性并提供更好的组件封装
HTML也是一样的。
JS-
Template.main.onCreated(function(){
this.text = new ReactiveVar("Default");
});
Template.main.helpers({
text: function(){
return Template.instance().text.get();
}
});
Template.button.events({
"click button": function(event, template){
var buttonText = template.$("button").text();
// search for a field named text in the closest parent template (main)
template.get("text").set(buttonText);
}
});
我们需要添加2个包才能使此代码工作:
meteor add reactive-var
meteor add aldeed:template-extension