我使用Handlebars.Js和Ember制作一个小应用程序。 First Handlebars生成模板
{{#each model}}
<div class="media">
{{#if isVoted}}
<a id="voteb" class="pull-left" href="#" {{action 'voteup'}}>
<i class="glyphicon glyphicon-chevron-down"></i>
<span id="votec">{{votecount}}</span>
</a>
{{else}}
<a id="voteb" class="pull-left" href="#" {{action 'votedown'}}>
<i class="glyphicon glyphicon-chevron-up"></i>
<span id="votec">{{votecount}}</span>
</a>
{{/if}}
<div class="media-body col-md-offset-1">
<h4 class="media-heading"><a id="linkt">{{title}}</a></h4>
</div>
</div>
{{/each}}
所以有按下投票按钮,这里点击按钮动作在Ember中触发
App.IndexController = Ember.ObjectController.extend({
actions: {
voteup: function(){
this.set('isVoted' , true);
},
votedown: function(){
this.set('isVoted' , false);
}
}
});
这将改变按钮的投票或不投票状态。
然而,它并没有改变按钮的投票/未投票状态。我在控制台中没有收到任何错误。那么这里的问题是什么?
还请告诉我一种检测点击哪个投票按钮的方法因为会有很多?
由于
答案 0 :(得分:1)
{{#each}}
循环遍历数组,因此应该是ArrayController
例如。
App.IndexController = Ember.ArrayController.extend({
})
虽然每个媒体项目都需要拥有自己的属性,但应该使用ObjectController
例如
App.MediaController = Ember.ObjectController.extend({
isVoted: false,
actions: {
voteup: function(){
this.set('isVoted' , true);
},
votedown: function(){
this.set('isVoted' , false);
}
}
});
您可以通过各种不同的方式实现这一目标,一种方法是将其封装在component
中,但在这种情况下,最简单的方法是告诉ArrayController
使用ObjectController
你定义为itemController
例如
App.IndexController = Ember.ArrayController.extend({
itemController: 'media'
})
这是一个有效的JSBin示例:http://jsbin.com/sufudo/2
答案 1 :(得分:0)
也许您应该在控制器中定义isVoted-var。
App.IndexController = Ember.ObjectController.extend({
//or get the initial value from somewhere
voteUp: false,
actions: {
voteup: function(){
this.set('isVoted' , true);
},
votedown: function(){
this.set('isVoted' , false);
}
}
});