删除和编辑挖空可观察数组中的项目
Remove and edit items in knockout observableArray
我在 observableArray workouts
中有一个数组exercises
。我想添加从中删除项目的功能。试图使其成为可观察数组:
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>
和视图模型:
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},
]);
相关文章:
- 有没有一种方法可以添加相同的项目val=“0”;4〃;到JavaScript中数组的每个对象
- 按不同项目对对象数组进行排序
- 使用JavaScript或jQuery检查单选按钮选择是否与数组中的项目匹配
- JS:从整个数组中每次得到5个项目,并得到平均值
- 使用圆中的数组更改背景颜色项目
- 编辑CSV数组中的项目-快速CSV node.js
- 我可以限制我添加到数组中的项目数量吗
- 使用javascript/jquery从现有数组中创建一个新数组,该数组保存项目存在的次数
- 什么's JavaScript数组中项目的作用域
- 将项目放入数组中
- 使用 id 和 Javascript 从数组中删除项目
- (角度.js)如何通过过滤器计算数组中有多少项目
- 如何通过迭代对象数组来删除某些项目
- Lodash 从与值数组不匹配的数组中获取项目
- 发布要形成的 n 个项目的数组
- 查找数组中项目包含子字符串的索引
- 我怎么能只保留符合特定条件的数组项目
- 关于将数组项目处理为分区的问题
- Php回显数组项目逐个点击(唯一)
- 连续删除数组项目(游戏障碍)