"is there any way to get knockout to somehow become callback aware?"
是的,您可以使用订阅。所有可观察对象、可观察数组和计算对象都继承自可订阅类型,因此您可以这样做:
var foo = ko.observable("foo");
foo.subscribe(function (newValue) {
// When foo updates, this function is called
});
通过订阅,您甚至可以设置临时订阅并在以后不再需要它们时取消它们。
var fooSub = foo.subscribe(function (newValue) {
// When foo updates, this function is called
});
// Somewhere else in the app...
fooSub.dispose();
默认情况下,订阅订阅一个名为“更改”的主题。这意味着当 observable 的值发生变化时,它会使用 newValue(因此是参数的名称)调用任何订阅者,但您也可以设置订阅主题“beforeChange”的订阅,以便在某个值之前执行逻辑变化。
foo.subscribe(function (oldValue) {
// Do logic on the oldValue here
}, null, 'beforeChange');
您可以在淘汰赛的文档中了解这一点。但您也可以根据需要订阅自定义主题。默认情况下,当 observables 的值改变时,'beforeChange' 和 'change' 主题会在值改变之前和之后触发(分别)。但是您可以订阅自定义主题,稍后您可以手动触发该主题,以通知任何收听该主题的订阅者。
foo.subscribe(function (value) {
// Do logic when observable notifies subscribers to the 'customTopic' topic
}, null, 'customTopic');
// Somewhere else in the app...
var value = "bar";
foo(value);
foo.notifySubscribers(value, 'customTopic');
通过这种方式,您可以在彼此没有直接引用的单独视图模型之间建立通信。这是我对如何执行此操作的粗略理解,您可以通过观看 Ryan Niemeyer 的提示和技巧视频了解更多信息。特别是订阅部分。
通过这种方式,您可以在淘汰赛中执行一种回调。还可以查看 Ryan 的Knockout-postbox库,该库将 observables 扩展为 subscribeTo 和 publishOn 这些主题。
您还可以查看 jQuery $.Deferreds,它是 $.ajax 请求使用的基础部分。这不是淘汰赛回调,而是一种回调。
让我知道这是否是您正在寻找的更多内容。