Knockout数据绑定串联的字符串数组

时间:2016-08-30 02:06:17

标签: javascript arrays knockout.js

如何在Knockout中数据绑定串联的字符串数组?我想做这样的事情:

HWND

显然语法是错误的,但是可以在不为每个人创建多个跨度的情况下执行上述操作吗?

1 个答案:

答案 0 :(得分:5)

你可以在data-bind中使用任何类型的有效javascript。所以想想可以做这样的事情:

选项1 - See fiddle

假设这样的模型:

var model = {
  people : ko.observableArray([
    {name: "Name1", age: 30},
    {name: "Name2", age: 31},
    {name: "Name3", age: 32},
  ])
}

ko.applyBindings(model);

我们可以这样做:

<span data-bind='text: people().map(function(p){return p.name + "," + p.age}).join(", ")'> </span>

选项2 - See fiddle

但是嵌入coplex内联javascript不是一个好习惯,我建议你创建一个像这样的计算属性

var model = {
  people : ko.observableArray([
    {name: "Name1", age: 30},
    {name: "Name2", age: 31},
    {name: "Name3", age: 32},
  ]),
}

model.allPeople = ko.computed(function() {
    return model.people().map(function(p){return p.name + "," + p.age}).join(", ");
});

ko.applyBindings(model);

HTML:

<span data-bind='text: allPeople'> </span>