问题在于您创建视图模型的方式。视图模型应该是自包含的,包括对其进行操作的函数。应该是这样的:
var ViewModel = function() {
var self = this;
self.type = ko.observable();
self.name = ko.observable();
self.content = ko.observable();
self.type.subscribe(function(newVal) {
// here you have access to all the viewmodel properties through self
});
return self;
};
这是一个使用var self=this; 模式的构造函数。要使用视图模型,您需要实例化它,即var vm = new ViewModel()。 (您可以省略new)。
当然你也可以定义一个函数,绑定到self,或者在构造函数中接收回调,绑定到self。在这种情况下,函数实现将具有可通过this 访问的视图模型,而不是 self,它将在函数体内未定义。
var doSomethignWithVm = function(newVal) {
// acces viewmodel via this
// you can also use newVal
};
您修改构造函数以将其作为回调接收:
var ViewModel = function(doSomethingCallback) {
self.type.subscribe(callback.bind(self));
};
这种模式没有多大意义,因为您的回调应该了解您的视图模型。在这种情况下,将订阅功能直接包含在模型中会更有意义。
编辑
注意:正如我在对 Joel Ramos Michaliszen 的回答的评论中提到的,这两个代码是等效的:
self.type.subscribe(callback.bind(self));
self.type.subscribe(callback.bind, self);
您可以通过在文件knockout/src/subscribales/subscribable.js 中查看knockout's gitbhub 中的subscribable 的源代码来检查。如果您寻找订阅实现,您会看到:
subscribe: function (callback, callbackTarget, event) {
// ...
boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
即如果您提供第二个参数,则它用于将第一个参数中传递的函数绑定到它。