星级评分绑定使用淘汰赛js

时间:2016-09-16 06:11:11

标签: javascript knockout.js knockout-mapping-plugin knockout-validation

我试图使用knockout js和ajax绑定星级评级,如果我手动分配值lik data = 3或data = 4,则星级评分是绑定,但是我从ajax获取的数据不会被绑定,但我从ajax结果中获取值并将其传递给viewmodel,它在下面不起作用是我的代码需要帮助。

 //HTML//

 <div id="divstarRating">
 <span data-bind="readonlyStarRating:starpoints"></span></a>
 </div>

     ///Custom Binding
ko.bindingHandlers.readonlyStarRating =
 {
  init: function (element, valueAccessor) {

   $(element).addClass("readonlyStarRating");
   for (var i = 0; i < 5; i++)
   $("<span>").appendTo(element);
             $("span", element).each(function (index) {
             var observable = valueAccessor();
             $(this).hover(
                 function () { $(this).prevAll().add(this).addClass("hoverChosen") },
                 function () { $(this).prevAll().add(this).removeClass("hoverChosen") }
             )
         });
     },
     update: function (element, valueAccessor) {
         var observable = valueAccessor();
         $("span", element).each(function (index) {
         $(this).toggleClass("chosen", index < observable());
         });
     }
 }
//viewModel

 function starRating(data) {
if (data != 0) {
    this.starpoints = ko.observable(data);
}
else {
    this.starpoints = ko.observable(1);
}
 }
 ko.applyBindings(new starRating(), document.getElementById('divstarRating'))

 //ajax///

$.ajax({
    type: "POST",
    dataType: "json",
    data: xxxx,
    url: xxxx+ 'api/xx/xxxxxx',
    success: function (data) {
      //I am getting the value and passing to viewModel
        return new starRating(data); 
    }
});

   //CSS//
.readonlyStarRating span { width:24px; height:24px; background-image:      url(../star.png); display:inline-block; cursor: pointer; background-position: -24px 0; }
.readonlyStarRating span.chosen { background-position: 0 0; }

1 个答案:

答案 0 :(得分:0)

您实际上有两个starRating实例。为了反映html中的值,您应该在传递给new startRating之前存储ko.applyBindings的实例。然后在您的ajax请求中使用该实例,而不是return new startRating(data)

或者您可以使用ko.dataFor获取viewModel的实例。

看起来像这样

...
   //in your ajax request    
   success: function (data) {
       var vm = ko.dataFor(document.getElementById('divstarRating'));
       vm.starpoints(data);
   }
...