2

我有一个包含子类的 ViewModel,我希望在修改子类中的一个属性时收到通知,如下所示:

var Person = function(){
  this.name = ko.observable("john doe");
  this.age = ko.observable(45);
};

var ViewModel = function() {
  this.Owner = ko.observable(new Person());

  this.Owner().subscribe(function(){
     alert("Someone updated owner");
  });    
};

var vm = new ViewModel();
vm.Owner().age(34);
​

但是上面的代码不起作用...

4

1 回答 1

2

你可以试试这个:

var ViewModel = function() {
    var self = this;
    self.Owner = ko.observable(new Person());

    self.test = ko.computed(function(){
        ko.toJS(self.Owner);
    });

    self.test.subscribe(function() {
        alert("Someone updated owner");
    });
};

这是工作小提琴:http: //jsfiddle.net/vyshniakov/hpKZj/

如果你想实现类似isDirty标志的东西,请阅读以下文章:http ://www.knockmeout.net/2011/05/creating-smart-dirty-flag-in-knockoutjs.html

于 2012-11-16T15:04:02.293 回答