0

我有一个 observableArray

self.workouts = ko.observableArray([
    {name: "Chest/Biceps", exercises:self.exercises1},
    {name: "Back/Triceps", exercises:self.exercises2},
    {name: "Legs/Shoulders", exercises:self.exercises3},
    ]);

exercises1看起来像这样:

self.exercises1 = ko.observableArray([
    {name: "bench press", sets:self.sets},
    {name: "machine chest press", sets:self.sets1},
    {name: "standing biceps curl", sets:self.sets2},
    {name: "machine biceps curl", sets:self.sets3}
]);

我想要的是为id每个对象添加一个唯一的exercises1,然后将它绑定到我的视图中。我尝试使用 attr 绑定,但没有成功。

我的视图如下所示:

<div class="content">
    <ul data-bind="foreach: workouts">
        <li class="name"><a class="name" data-bind="text:name"></a>
            <ul class="hhide" data-bind="foreach: exercises">
                <li class="name_ex"><a data-bind="text:name"></a>
                <div class="hhide">
                    <input id ="weight" type="text" placeholder="weight(kg)">
                    <span id="append">x</span>
                    <input id ="reps" type="text" placeholder="reps">
                    <button id="sets" data-bind="click: $root.addSet">Add set</button>
                    <div data-bind="foreach: sets">
                        <div id="sets" class="remove" data-bind="click: $root.removeSet">delete</div>
                        <div data-bind="visible: !editing(), text: name, click: edit"></div>
                        <input data-bind="visible: editing, value: name, hasFocus: editing" />
                    </div>
                    </div>
                </li>
            </ul>       
    </ul>
</div>

谢谢!

4

1 回答 1

1

这是你想要的?(小提琴:http: //jsfiddle.net/U7EFz/4/

html:

<div class="content">
    <ul data-bind="foreach: workouts">
        <li class="name"><a class="name" data-bind="text:name"></a>
            <ul class="hhide" data-bind="foreach: exercises">
                <li class="name_ex">
                    <a data-bind="text:name, attr:{id:uniqueId}"></a>                                                                                               
                    | uniqueId:
                    <span data-bind="text:uniqueId"></span>
                </li>
            </ul>       
        </li>
    </ul>
</div>

js:

var VM = function(){
    var self = this;
    var idCounter = 0;
    self.getId = function(){        
        return "id" + (++idCounter);
    }

    self.exercises1 = ko.observableArray([
        {name: "bench press", uniqueId:"id1"},
        {name: "machine chest press", uniqueId:"id2"},
        {name: "standing biceps curl", uniqueId:"id3"},
        {name: "machine biceps curl", uniqueId:"id4"}
    ]);    

    self.workouts = ko.observableArray([
        {name: "Chest/Biceps", exercises:self.exercises1},
        {name: "Back/Triceps", exercises:self.exercises1},
        {name: "Legs/Shoulders", exercises:self.exercises1},
        ]);      
}

ko.applyBindings(new VM())
于 2013-11-03T21:23:31.023 回答