Data binding 移除项后,Aurelia未显示正确的数组表示形式
我有一个数组中的项目列表 单击视图中的项目时,我正在尝试删除此项目 看法Data binding 移除项后,Aurelia未显示正确的数组表示形式,data-binding,aurelia,Data Binding,Aurelia,我有一个数组中的项目列表 单击视图中的项目时,我正在尝试删除此项目 看法 .pull()和.remove()(使用lodash)都将删除数组中的项,但不会更新ui .shift()设法从数组中删除一个项,并正在更新UI 为什么Aurelia在使用lodash时,即使我删除了该项,也不更新UI 附录:如果我两次单击同一项,那么可能值得注意的是\uincludes第一次为true,第二次为false 使用ES2015 Sets另一种方法是使用ES2015 Set数据 结构。它可以用一个值数组初始化,
.pull()
和.remove()
(使用lodash)都将删除数组中的项,但不会更新ui
.shift()
设法从数组中删除一个项,并正在更新UI
为什么Aurelia在使用lodash时,即使我删除了该项,也不更新UI
附录:如果我两次单击同一项,那么可能值得注意的是\uincludes
第一次为true,第二次为false
使用ES2015 Sets另一种方法是使用ES2015 Set数据
结构。它可以用一个值数组初始化,并且
prototype甚至提供了删除特定值的删除方法
然而,集合的语义不同于常规数组。通过
根据定义,集合是唯一值的集合。因此,
从不包含重复项。如果您需要一个允许
重复的值、集合是错误的数据结构
我现在正在为此使用一个集合,它允许我使用.add()
和.delete()
。我只需要记住,每件事都必须是独一无二的(好吧,就我而言)
虽然lodash不起作用,但我仍然想理解为什么操纵数组,但我会在其他时间对此进行研究
附录 您还可以使用原型:
interface Array<T> {
remove(itemToRemove: T): Array<T>;
}
(<any>Array.prototype).remove = function (itemToRemove) {
const index = this.indexOf(itemToRemove);
if (index !== -1) {
this.splice(index, 1);
}
return this;
}
接口数组{
移除(itemToRemove:T):数组;
}
(Array.prototype).remove=函数(itemToRemove){
const index=this.indexOf(itemToRemove);
如果(索引!=-1){
这是一个拼接(索引1);
}
归还这个;
}
Aurelia可以使用$index
变量在中继器中为您提供当前项目的索引。然后,只需使用ES2015提供的内置阵列方法:
看法
我相信你的问题在于变量的范围 _.pull和u.remove正在返回数组的新实例 试一试
this.stack=\.remove(this.stack,lootItem)代码>当ES2015内置此功能时,为什么要使用lodash?使用本机函数,您的代码就会工作。我熟悉很多lodash方法,这就是我决定引入它的原因,这是否意味着在标准ES方法之外操纵数组将不起作用?现在看来我可以使用filter并像这样操作数组:this.stack=this.stack.filter(item=>item!=lootItem)代码>。但是我觉得它没有简单的.remove()
那么清晰。我不熟悉lodash的内部结构,但我已经发布了一个答案,说明使用内置数组方法是多么简单。干杯根据文档,它应该改变数组,检查变量表明它实际上删除了该项,但它没有反映在视图中。
takeItem(lootItem){
this.eventAggregator.publish(new ItemTaken(lootItem));
console.log(_.includes(this.stack, lootItem)); //true
_.pull(this.stack, lootItem); //removes item and fails to update the ui
_.remove(this.stack, lootItem); //removes item and fails to update the ui
this.stack.shift(); //removes first item and updates the ui
}
interface Array<T> {
remove(itemToRemove: T): Array<T>;
}
(<any>Array.prototype).remove = function (itemToRemove) {
const index = this.indexOf(itemToRemove);
if (index !== -1) {
this.splice(index, 1);
}
return this;
}
<div class="lootItem" repeat.for="lootItem of stack">
<div class="noselect" click.delegate="$parent.takeItem($index, lootItem)">
<i class="fa fa-diamond"></i> ${lootItem.value}
</div>
</div>
takeItem($index, lootItem){
this.eventAggregator.publish(new ItemTaken(lootItem));
this.stack.splice($index, 1);
}