我期待用户界面显示"再见"。相反,它会显示"你好吗?"。为什么会这样?在淘汰赛中,处理单个订阅是否会阻止观察者工作?
这里是一名掠夺者:https://plnkr.co/edit/V5g5aQ5wxPGaRL31pUKj
这是我的代码:
<!DOCTYPE html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
</head>
<body>
<p>
message: <span data-bind="text: message"></span>
</p>
<p>
messageChanged: <span data-bind="text: messageChanged"></span>
</p>
</body>
<script>
var viewModel = {
message: ko.observable('Hello'),
messageChanged: ko.observable(0)
};
var dispose = viewModel.message.subscribe(function _subscribe(newValue) {
viewModel.messageChanged(viewModel.messageChanged() + 1);
});
ko.applyBindings(viewModel);
viewModel.message('How are you?');
dispose();
viewModel.message('Good-bye');
</script>
</html>
我希望这是有效的代码。这是文档所说的内容:
答案 0 :(得分:1)
我处理不当。我应该调用subscribe
结果的dispose
属性,而不是调用subscribe
的结果。
如果您愿意,也可以终止订阅:首先将返回值捕获为变量,然后您可以调用其dispose函数,例如:
var subscription = myViewModel.personName.subscribe(function(newValue) { /* do stuff */ });
// ...then later...
subscription.dispose(); // I no longer want notifications
这是一个纠正过的傻瓜: https://plnkr.co/edit/hsdESPX1F0k09lH4hThl
以下是更正后的代码:
<!DOCTYPE html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
</head>
<body>
<p>
message: <span data-bind="text: message"></span>
</p>
<p>
messageChanged: <span data-bind="text: messageChanged"></span>
</p>
</body>
<script>
var viewModel = {
message: ko.observable('Hello'),
messageChanged: ko.observable(0)
};
var subscription = viewModel.message.subscribe(function _subscribe(newValue) {
viewModel.messageChanged(viewModel.messageChanged() + 1);
});
ko.applyBindings(viewModel);
viewModel.message('How are you?');
subscription.dispose();
viewModel.message('Good-bye');
</script>
</html>
答案 1 :(得分:1)
您无需调用dispose方法。在knockout observable中自动更新UI中的值而不显式调用它们。可能会解决您的问题。这也将更新您的邮件计数
taxBracket