2

我有下一个模型:

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>
4

3 回答 3

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>');
        });
    }
};
于 2013-03-07T19:22:17.497 回答
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)">
于 2013-03-07T19:22:25.777 回答
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>

希望这就是你要找的。

干杯! 苏杰

于 2013-03-07T20:24:57.537 回答