调试控制台输出显示选项更改确实更改了挖空数据,并且可以通过按下html页面最后一行上的按钮强制计算运行来查看更改结果但由于某种原因{显示在html的倒数第二行的{1}}不会像我期望的那样自动更新。
任何帮助将不胜感激!
ko.computed
function CustomBindingViewModel() {
var self = this;
self.range = [1, 2, 3, 4, 5];
self.opts = [
"Functionality, compatibility, pricing - all that boring stuff",
"How often it is mentioned on Hacker News",
"Number of gradients/dropshadows on project homepage",
"Totally believable testimonials on project homepage"
];
self.optionRange = 5;
self.options = ko.observableArray();
self.opts.forEach(function(option) {
self.options.push({
option: option,
importance: 2
});
});
self.points = function() {
var sum = 0;
var sumStr = "";
self.options().forEach(function(option) {
sum += option.importance;
sumStr += option.importance;
});
console.log(sumStr);
return 10 - sum;
};
}
ko.applyBindings(new CustomBindingViewModel());
.points {
font-weight: bold;
}
.select {
text-align: center;
}
答案 0 :(得分:2)
虽然数组是一个可观察的数组,但数组中的值是不可观察的。
使数组中项目的importance
属性也可观察,因为这是你想要观察的内容。
//...other code removed for brevity
self.options = ko.observableArray();
self.opts.forEach(function(option) {
self.options.push({option:option, importance:ko.observable(2)}); //<-- NOTE THIS HERE
});
//...other code removed for brevity
以便在importance
值更改时触发事件。
然后,您需要更新点的计算方式。
//...other code removed for brevity
self.points = function() {
var sum = 0;
var sumStr = "";
self.options().forEach(function (option) {
sum += option.importance(); //<-- NOTE THE BRACES
sumStr += option.importance(); //<-- NOTE THE BRACES
});
console.log(sumStr);
return 10 - sum;
};
//...other code removed for brevity
以下是完成的js fiddle