我有下一个型号:
var simpleModel = function(){
var self = this;
self.name = "Simple model";
self.attributes = {
attr1: ko.observable("1"),
attr2: ko.observable("2"),
attr3: ko.observable("3")
};
}
我希望能够枚举此模型的attributes
属性并显示密钥和值,如下所示:
<div>
<span>attr1</span><span>1</span>
<span>attr2</span><span>2</span>
<span>attr3</span><spam>3</span>
</div>
当我在一个对象上使用时,我试图根据javascript的for循环行为来解决这个问题,但是失败了:
<div data-bind="foreach: { data: designAttributes, as: 'dAttr' }">
<span data-bind="text: $index"></span>
<span data-bind="text: dAttr[$index]"></span>
</div>
答案 0 :(得分:1)
自定义绑定:
<div data-bind="createSpan">
ko.bindingHandlers.createSpan =
{
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext)
{
for(var item in valueAccessor())
{
$(element).append('<span data-bind="text:' + valueAccessor()[item] + '"></span>');
});
}
};
答案 1 :(得分:1)
我担心foreach是仅为数组创建的,因此您需要将对象转换为数组的功能。 jsFiddle
window.objToArray = function (obj) {
var result = [];
for (var i in obj) {
result.push({ key: i, value: obj[i]});
}
return result;
};
并在绑定中使用它们:
<ul data-bind="foreach: window.objToArray(items)">
答案 2 :(得分:1)
使用计算的observable获取所需的结构并绑定到该结构。我冒昧地修改你的JS并使self.attributes成为一个可观察的。
这是小提琴。
http://jsfiddle.net/sujesharukil/A846H/
var simpleModel = function(){
var name = 'Simple model',
attributes = ko.observable({
attr1: ko.observable('1'),
attr2: ko.observable('2'),
attr3: ko.observable('3')
}),
splitAttributes = ko.computed(function(){
var splitAttribs = [];
for(var attr in attributes()){
splitAttribs.push({
name: attr,
val: attributes()[attr]
});
}
return splitAttribs;
}),
vm = function(){};
vm.name = name;
vm.attributes = splitAttributes;
return vm;
}
ko.applyBindings(new simpleModel());
这是HTML的绑定。
<div data-bind="foreach: attributes">
<span data-bind="text: name"></span> = <span data-bind="text: val"></span> <br/>
</div>
希望这就是你要找的东西。
干杯! SUJ