在视图模型Knockout中使用自定义对象

时间:2011-12-09 14:41:24

标签: knockout.js

我是从Silverlight来到Knockout.js。当我在Silverlight中创建ViewModel时,我经常会遇到这样的事情:

public class MyViewModel : ViewModel
{
  private MyCustomClass custom = null;
  public MyCustomClass Custom
  {
    get { return custom; }
    set { custom = value;
      NotifyPropertyChanged("MyCustomClass");
    }
  }
}

<TextBox Text="{Binding Path=Custom.PropertyName, Mode=TwoWay}" />

但是,我不确定如何在Knockout.js中做同样的事情。目前,我有:

<input type="text" data-bind="value:propertyName" />

var viewModel = {
  custom: {
    propertyName:""
  }
}

1 个答案:

答案 0 :(得分:1)

你当然可以做你在那里的工作,但你想要绑定到value: custom.propertyName,除非你已经使用模板或KO中的custom绑定将上下文更改为with 1.3。

执行此操作的典型方法是为自定义对象创建构造函数,如:

var Person = function(first, last) {
  this.first = ko.observable(first);
  this.last = ko.observable(last);
};

var viewModel = {
  people: ko.observableArray([
     new Person("Bob", "Smith"),
     new Person("Ted", "Jones")
  ])
};