Knockout.js自定义绑定“未调用更新函数”

时间:2017-04-17 14:23:16

标签: javascript jquery knockout.js knockout-2.0

我有下面的自定义绑定,它的星级,在我的页面加载初始化和更新被调用但在那之后,只调用init函数而不是更新函数。我需要更新函数,其中有“Chosen”类toggleclass,它在选中后添加类到星形绑定。亲切地建议,我正面临着问题。

    <div data-role=view id="view1">
    <div id="divstarRating" data-bind="click:selectStar">
    <span id="Star" data-bind="readonlyStarRating:starpoints"> </span>
    </div>
    </div>
.starRating span {
  width: 24px;
  height: 24px;
  background-image: url(../star.png);
  display: inline-block;
  cursor: pointer;
  background-position: -24px 0;
 }

 .starRating span.chosen {
  background-position: 0 0;
 } 

 .starRating:hover span {
 background-position: -24px 0;  
transform: rotate(-15deg) scale(1.3);
}

.starRating:hover span.hoverChosen {
 background-position: 0 0;
 transform: rotate(-15deg) scale(1.3);
  }

   function StarViewModel() {
    self.starpoints= ko.observable();

    self.selectStar=function(){
    window.location.href="view1"
     //here i get selected star value
      starValue=self.starpoints()

      //here i am using ajax to post star value
           $.ajax({
                type: "POST",
                dataType: "json",
                data: Model,
                url: serverUrl + 'xxx/xx/xx',
                success: function (data) {
                    $('#loading-image').hide();
                  // after susccees of post success ajax data consist of star rating value
                   self.starpoints= ko.observable(data);
                },
      }
   }

    $(document).ready(function () {
     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 = new StarViewModel();
    ko.applyBindings(ViewModel);
  });

1 个答案:

答案 0 :(得分:0)

来自你的jsFiddle,在你的okay()函数中:

self.okay = function ()
{
    data = self.UserFeedpoint
    self.UserFeedpoints = ko.observable(data);
    window.location.href = "#home1"
}

您将使用新的observable覆盖UI绑定的observable。您只需要更改它以更新现有的observable。像:

self.okay = function ()
{
    data = self.UserFeedpoint
    self.UserFeedpoints(data);
    window.location.href = "#home1"
}