Reputation: 4050
I'm using Handlebars.Js and Ember to make a small app. First Handlebars generate the template
{{#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}}
So there are vote up down buttons, here when a button is clicked action is triggered in Ember
App.IndexController = Ember.ObjectController.extend({
actions: {
voteup: function(){
this.set('isVoted' , true);
},
votedown: function(){
this.set('isVoted' , false);
}
}
});
This will change the voted or not state of the button.
However it doesn't change the vote/not voted state of the button. I don't get any errors in the console. So what's the problem here?
And also please tell me a way to detect which vote button is clicked As there will be many?
Thanks
Upvotes: 0
Views: 166
Reputation: 1074
The {{#each}}
loops through an array, so should be an ArrayController
eg.
App.IndexController = Ember.ArrayController.extend({
})
Whereas each media item needs to have it's own properties, so should be using an ObjectController
eg
App.MediaController = Ember.ObjectController.extend({
isVoted: false,
actions: {
voteup: function(){
this.set('isVoted' , true);
},
votedown: function(){
this.set('isVoted' , false);
}
}
});
You can achieve this in various different ways, one would be to encapsulate it in a component
, but in this case the most simple could be to tell the ArrayController
to use the ObjectController
you have defined as the itemController
eg
App.IndexController = Ember.ArrayController.extend({
itemController: 'media'
})
Here is a working JSBin example: http://jsbin.com/sufudo/2
Upvotes: 1
Reputation: 192
Maybe you should define the isVoted-var in the controller.
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);
}
}
});
Upvotes: 0