【问题标题】:Remove and edit items in knockout observableArray删除和编辑淘汰赛 observableArray 中的项目
【发布时间】:2013-11-01 16:49:18
【问题描述】:

我在 observableArray workouts 中有一个数组 exercises。我想添加从中删除项目的功能。试图使它成为一个 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/

谢谢!

【问题讨论】:

    标签: javascript mvvm view knockout.js viewmodel


    【解决方案1】:

    对于 removeExercise,bindingContext 应该是 $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},
    ]);
    

    【讨论】:

    • 谢谢,它有效。我有这个想法。但是我怎样才能启用编辑呢?
    • 是的,但不需要输入字段,只需单击锻炼或锻炼名称即可编辑,然后单击其他位置并应用更改。
    • 非常感谢!现在我将尝试理解代码中的所有内容:) 所以你创建了一个函数构造函数Record,然后你用这个函数创建了新对象new Record("Exercise1.1")
    • 是的,没错,因为 Record 代码会变得相当复杂,所以将它放在一个单独的函数中会更容易。如果有用,请不要忘记接受/投票。
    • 好吧,就做 self.exercises()[0].name()
    猜你喜欢
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-16
    • 2014-08-05
    • 1970-01-01
    相关资源
    最近更新 更多