在以下代码中,有没有办法明确订阅comp
到b
,以便点击change a
然后点击change b
将始终触发comp
(无论在change a
之前点击change b
多少次?
[请注意,我不是在寻找一个解决方案,比如从self.b()
块(或其他类似的技巧)中取出else
,而是明确调用某些函数,我想这类似的东西到subscribe
]
var ViewModel = function () {
var self = this;
self.a = ko.observable(true);
self.b = ko.observable(1);
self.changeA = function () {
console.log("changeA clicked");
self.a(!self.a());
}
self.changeB = function () {
console.log("changeB clicked");
self.b(0);
}
self.comp = ko.computed(function () {
if (!self.a()) {
console.log("a");
// ... some code that computes a ...
}
else {
console.log("b");
var b = self.b();
// ... some code that computes b ...
}
return "hello";
})
}
vm = new ViewModel();
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<button data-bind="click: changeA, text: 'change a'"></button>
<button data-bind="click: changeB, text: 'change b'"></button>
答案 0 :(得分:0)
使用订阅者和其他可观察者是否有任何问题?
$item['price'] = 0;
/*code to get item information goes in here*/
if((string)$item['price'] == 'e') {
$item['price'] = -1;
}
var ViewModel = function() {
var self = this;
self.a = ko.observable(true);
self.b = ko.observable(1);
self.changeA = function() {
self.a(!self.a());
}
self.changeB = function() {
self.b(0);
}
self.comp = ko.observable();
self.b.subscribe(function(newVal) {
console.log('b was changed to ', newVal);
self.comp(newVal);
})
}
vm = new ViewModel();
ko.applyBindings(vm);
答案 1 :(得分:0)