knockout.js data-bind每个对象数组

时间:2017-05-25 13:04:41

标签: knockout.js

我让json回来了:

operator==

然后在我的标记中我有

operator==

{ "school": { "students":[{"firstName":"John", "lastName":"Doe"},"firstName":"Jane", "lastName":"Doe"}] } } 一定不对,因为它不起作用。有人可以帮我解释语法吗?

2 个答案:

答案 0 :(得分:0)

淘汰赛并不像那样。您需要先将JSON构建到某些对象中,然后才能对其使用struct deep_equal_by_tie { template<class T> using enable = std::enable_if_t<std::is_base_of<equal_by_tie, T>,bool>; template<class T> friend enable<T> deep_equal( T const& lhs, T const& rhs ) { // code to call deep_equal on each tie // deep_equal on non-pointer basic types defined as == // deep_equal on pointers is to check for null (nulls are equal) // then dereference and deep_equal // ditto for smart pointers // deep_equal on vectors and other std containers is to check size, // and if matches deep_equal on elements } }; 绑定。

例如,使用您需要的属性创建学生对象:

foreach

然后当你有了你的JSON字符串(可能是你的AJAX加载的成功回调)时,你可以从数据中创建这些学生对象的集合:

function Student(firstName, lastName) {
    this.firstName = ko.observable(firstName);
    this.lastName = ko.observable(lastName);
}

然后,您可以像在小例子中一样使用school.students = ko.utils.arrayMap(json, function(item) { return new Student(item.firstName, item.lastName); }); 绑定。当然我假设你已经创建了一个viewmodel并正确使用了foreach

答案 1 :(得分:0)

他们有一个淘汰映射插件。在下面运行片段。

var data = {
  "school": {
    "students": [{
      "firstName": "John",
      "lastName": "Doe"
    }, {
      "firstName": "Jane",
      "lastName": "Doe"
    }]
  }
}
var viewModel = ko.mapping.fromJS(data);

$(document).ready(function() {
  ko.applyBindings(viewModel);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script>

<ul data-bind="foreach: school.students">
  <li><span data-bind="text: firstName"></span><span data-bind="text: lastName"></span></li>
</ul>

http://knockoutjs.com/documentation/plugins-mapping.html