繁体   English   中英

删除和编辑基因剔除observableArray中的项目

[英]Remove and edit items in knockout observableArray

我有一个数组exercises observableArray内workouts 我想添加从其中删除项目的功能。 试图使其成为一个observableArray:

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/

谢谢!

bindingContext应该是removeExercise的$ root,练习应该是一个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},
]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM