I have a semi-comprehensive KO setup. But so far I have only used KO to present the data.
Now I have a need to increase/decrease values on my model.
Here’s my Model:
SharedItem: function (data) {
var self = {};
...
self.rating = ko.observable(data.Rating);
...
return self;
}
And here’s my View
ItemsViewModel: function (json) {
var model = {};
model.shareditems = ko.observableArray();
var mappedSharedItems = [];
var parsedData = $.parseJSON(json);
$.each(parsedData, function (key, val) {
var newSharedItems = new SharedItem(val);
mappedSharedItems.push(newSharedItems);
});
//My function to vote
model.voteUp = function(item) {
item.rating += 1;
}
model.shareditems(mappedSharedItems);
return model;
}
And my view is applied like any standard Knockout binding (response is my ajax response that I pass to the viewmodel):
var viewModel = ItemsViewModel(response);
ko.applyBindings(viewModel, $('#ItemListWrapper')[0]);
But I can’t seem to figure out how to make my voteUp function increase the rating number.
And important note: The rating value is a string, from the server. But I guess I could be able to just use parseInt on it.
Can anyone point my in a direction on how to make this function increase a value of the model’s property?
Thanks in advance
Edit: If you want to see the HTML where I call voteUp here it is:
<div class="Vote">
<a href="#" data-bind="click: $parent.voteUp">+1</a>
</div>
Edit 2: My solution:
item.rating(parseInt(item.rating()) + 1);
You need to use the observable syntax to do this: