【发布时间】:2017-04-17 14:23:15
【问题描述】:
我有以下自定义绑定,它的星级,在页面加载时为我调用了 init 和 update,但之后,只调用了 init 函数而不是 update 函数。我需要更新功能,其中有类“选择”切换类,选择后将类添加到星形绑定。我在这个好意的建议中遇到了问题。
<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);
});
【问题讨论】:
-
更新代码看起来不错。我认为问题出在其他地方。
-
这是一个 jsFiddle。绑定的更新部分按预期工作。 jsfiddle.net/jlspake/9do8aoeb
-
@thanks for your time,但它对我不起作用,我有 2 个视图,在第一个视图中我有绑定处理程序,在第二个视图中我有,第一次点击更新功能,但选择开始评分后,我被重定向到第一个视图,再次返回第二个视图查看,当我单击增量或减量时不会调用更新或更新函数,我不知道为什么第二次更新不起作用
-
显示你的javascript
-
@我已经更新了我的代码,我的问题是更新功能已经切换选择的类,所以当用户选择 satr 评级时我需要一直更改
标签: javascript jquery knockout.js knockout-2.0