我正在尝试使用raty jQuery插件在KnockoutJS中创建自定义绑定,以对电影进行星级评分。 raty插件的常规实现如下所示:
$('.raty').raty();
<div class="raty" data-rating="3"></div>
那会给你这样的东西...
<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>
我有一部
observableArray
电影,集合中的每部电影都具有UserMovies.Rating
。当用户更新星级,然后更新电影UserMovies.Rating
中的observableArray
值时,我正在努力想出一种具有bindingHandler句柄的方法。这是我对实现和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'));
}
};
最佳答案
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
$(element).data("rating",value);
$(element).raty(options);
$(element).delegate('click', 'img', function() {
valueAccessor($(element).raty('score'));
});
}
};
关于javascript - 在KnockoutJS中为jQuery插件创建自定义绑定(bind),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13779700/