在KnockoutJS中为jQuery插件创建自定义绑定

时间:2012-12-08 17:04:35

标签: javascript knockout.js

我正在尝试使用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'));
    }
};

3 个答案:

答案 0 :(得分:1)

这段代码非常适合我:

ko.bindingHandlers.raty = {
   init: function (element, valueAccessor, allBindingsAccessor) {
      var options = allBindingsAccessor().ratyOptions || {};
      var value = ko.utils.unwrapObservable(valueAccessor());

      $(element).raty(options);
      $(element).raty("score", value);

      ko.utils.registerEventHandler(element, "click", function () {
          var observable = valueAccessor();
          observable($(element).raty("score"));
      });
    }
};

答案 1 :(得分:0)

不确定你打算用这条线做什么,但可以替换这一行:

ko.bindingHandlers.attr.update(element, { 'data-rating': value }); 

只有:

$(element).data("rating",value);

对于更新,raty是否会针对评分更改公开事件?如果是这样,您可以将其绑定在init中。否则,您可以尝试绑定click事件。

答案 2 :(得分:0)

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'));
        });
    }
};