I’m trying to create a custom binding in KnockoutJS using the raty jQuery plugin to do star ratings for movies. The normal implementation for the raty plugin would look like this…
$('.raty').raty();
<div class="raty" data-rating="3"></div>
and that would give you something like this…
<div class="raty" data-rating="3" style="cursor: pointer; width: 100px;">
<img src="/raty/img/star-on.png" alt="1" title="bad">
<img src="/raty/img/star-on.png" alt="2" title="poor">
<img src="/raty/img/star-on.png" alt="3" title="regular">
<img src="/raty/img/star-off.png" alt="4" title="good">
<img src="/raty/img/star-off.png" alt="5" title="gorgeous">
<input type="hidden" name="score" value="3">
</div>
I have an observableArray of movies, with each movie in the collection having UserMovies.Rating. I’m struggling to come up with a way to have the bindingHandler handle when users update the star rating and then updating the UserMovies.Rating value in the movies observableArray.
This is my attempt at the implementation and bindingHandler…
<div class="raty" data-bind="raty: UserMovies[0].Rating, ratyOptions: { cancel: true, half: true, size: 24 }"></div>
ko.bindingHandlers.raty = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = allBindingsAccessor().ratyOptions || {};
var value = ko.utils.unwrapObservable(valueAccessor());
// the line below throws Syntax error: Invalid label
ko.bindingHandlers.attr.update(element, { 'data-rating': value });
$(element).raty(options);
// how to fire upate function when user changes star ratings?
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
valueAccessor($(element).raty('score'));
}
};
1 Answer