简体   繁体   English

JS对象与使用Knockout JS的HTML数据绑定

[英]JS object to HTML data binding with Knockout JS

I have a JS object constructed from XML. 我有一个从XML构造的JS对象。

How do I bind that JS object to html? 如何将JS对象绑定到html?

Example: ViewModel: 示例:ViewModel:

  vm: {
    a: ko.observable()
  }

JS (of the model): JS(模型):

aObj : {
  item1: [ { n: 'a1', v: 'v1'}, { n:'a2', v:'v2' } ],
  item2: [ ]
}

JS (binding logic): JS(绑定逻辑):

vm.a(aObj);

HTML: HTML:

<div data-bind="with: vm.a">
  <div data-bind="foreach: item1">
     <div data-bind="text: n"></div>
  </div>
</div>

I cannot loop over the array elements of item1 我无法遍历item1的数组元素

What am I doing wrong? 我究竟做错了什么? I just get the following computed DOM: 我只是得到以下计算的DOM:

<div data-bind="with: vm.a">
  <div data-bind="foreach: item1">
  </div>
</div>

Seems to be working: http://jsfiddle.net/tpLVC/2/ . 似乎可以正常使用: http : //jsfiddle.net/tpLVC/2/

Do you get any errors in the console? 控制台中是否出现任何错误? In the html in the fiddle, notice that the with binding is with: a . 在小提琴的html中,请注意with绑定是with: a If your top level viewModel has the a property, then you should use it like this. 如果您的顶级viewModel具有属性,那么您应该像这样使用它。

If you have a top level viewModel with a vm property, only then will the with: vm.a work. 如果您具有带vm属性的顶级viewModel,则只有这样with: vm.a工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM