0

ノックアウトjsとajaxを使用してスター格付けをバインドしようとしていますが、私は値を手動でlikデータ= 3またはデータ= 4に割り当てると星格付けがバインドされますが、 Ajaxからバインドされていないが、私はajaxの結果から値を得て、viewmodelに渡すと、以下のコードではコードが必要になる。ノックアウトjsを使用したスター格付けバインディング

//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; } 
+0

そのように見えます

が見えます。 – janmvtrinidad

答えて

0

実際にはstarRatingという2つのインスタンスがあります。 htmlの値を反映させるには、ko.applyBindingsに渡す前にnew startRatingのインスタンスを保存する必要があります。次に、return new startRating(data)ではなく、そのインスタンスをajaxリクエストで使用します。

ko.dataForを使用すると、viewModelのインスタンスを取得できます。あなたはどのように[jQueryのAjaxの作品](http://api.jquery.com/jquery.ajax/)理解始めよ必要のようにそれはこの

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

あなたの時間のための@おかげで、それは私の問題を解決しました –

関連する問題