删除并编辑knockout observableArray中的项目

时间:2013-10-23 12:06:03

标签: javascript mvvm view knockout.js viewmodel

我在observableArray exercises中有一个数组workouts。我想添加从中删除项目的功能。试图使它成为一个可观察的阵列:

self.exercises = ko.observableArray();

并添加了删除项目的功能:

self.removeExercise = function() {
        self.exercises.remove(this);
    };

但没有任何反应。虽然相同的功能适用于workouts父数组。 除此之外,我还有一个简单的函数来编辑数组中的项目,如下所示:

this.edit = function() { this.editing(true) }

并尝试在我的视图中绑定它:

<span data-bind="text: name, click: edit"> </span>

但它不起作用。问题出在哪里?

这是我的观点

<div class="content">
    <ul data-bind="foreach: workouts">
        <li>
            <span data-bind="text: name, click: edit"> </span>
                 <a href="#" data-bind="click: $parent.removeWorkout">Remove</a>
             <ul data-bind="foreach: exercises">
                 <li>
                     <span data-bind="text: name"> </span>
                     <a href="#" data-bind="click: $parent.removeExercise">remove</a>
                 </li>
             </ul>
        </li>
    </ul>   
</div>

和ViewModel:

function AppViewModel() {   
    var self = this;

    self.workouts = ko.observableArray([
    {name: "Workout1", exercises:[
        { name: "Exercise1.1" },
        { name: "Exercise1.2" },
        { name: "Exercise1.3" }
    ]},
]);

    self.exercises = ko.observableArray();

    self.removeWorkout = function() {
        self.workouts.remove(this);
    };
    self.removeExercise = function() {
        self.exercises.remove(this);
    };

    this.editing = ko.observable(false);
    this.edit = function() { this.editing(true) }    
}

ko.applyBindings(new AppViewModel);

以下是jsfiddle的示例: http://jsfiddle.net/c9fQB/

谢谢!

1 个答案:

答案 0 :(得分:1)

bindingContext应该是$ root for removeExercise,而exercise应该是observableArray。试试这个:http://jsfiddle.net/Ag8rr/

观察者代码:

    self.exercises = ko.observableArray([
        { name: "Exercise1.1" },
        { name: "Exercise1.2" },
        { name: "Exercise1.3" }
    ]);    

    self.workouts = ko.observableArray([
    {name: "Workout1", exercises:self.exercises},
]);