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

发布于 2024-12-20 13:16:57 字数 592 浏览 0 评论 0原文

我从 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:""
  }
}

I am coming from Silverlight to Knockout.js. When I would create ViewModels in Silverlight, I would often times have something like this:

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}" />

However, I'm not sure how to do the same kind of thing in Knockout.js. Currently, I have:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

唠甜嗑 2024-12-27 13:16:57

您当然可以执行您现有的操作,但您可能希望绑定到 value: custom.propertyName ,除非您已经使用模板或 custom 将上下文更改为 custom code>with KO 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")
  ])
};

You can certainly do what you are have there, but you would want to bind to value: custom.propertyName unless you have already changed context to custom using a template or the with binding in KO 1.3.

A typical way to do this is to create constructor functions for your custom object like:

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")
  ])
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文