从Aurelia中的父部件中更新可观察的收藏
为了更好地理解Aurelia组件之间的交互作用,我将todo列表应用程序的列表组件分开了nofollow noreferrer“>快速启动文档进入其自己的类和相应的视图。但是这样做会导致视图不更新新元素添加到列表中。
我修改的代码如下:
app.html:
<template>
<require from="./todo-list"></require>
<h1>Todo list</h1>
<form submit.trigger="addTodo()">
<input type="text" value.bind="todoDescription">
<button type="submit" disabled.bind="!todoDescription">Add Todo</button>
</form>
<todo-list></todo-list>
</template>
app.ts:
import { TodoList } from "todo-list";
export class App {
todoList: TodoList = new TodoList();
todoDescription = '';
addTodo() {
if (this.todoDescription) {
this.todoList.addOne(this.todoDescription);
this.todoDescription = '';
}
}
}
todo-list.html
<template>
<ul>
<li repeat.for="todo of todos">
<input type="checkbox" checked.bind="todo.done">
<span css="text-decoration: ${todo.done ? 'line-through' : 'none'}">
${todo.description}
</span>
</li>
</ul>
</template>
todo-list.ts:
export interface Todo {
description: string;
done: boolean;
}
export class TodoList {
todos: Todo[] = [
{ description: "Make bed", done: true },
{ description: "Take out trash", done: false }
];
addOne(todoDescription: string) {
this.todos.push({
description: todoDescription,
done: false
});
}
}
原始的工作代码如下:
app.ts:
export interface Todo {
description: string;
done: boolean;
}
export class App {
todos: Todo[] = [
{description: "Make bed", done: true},
{description: "Take out trash", done: false}
];
todoDescription = '';
addTodo() {
if (this.todoDescription) {
this.todos.push({
description: this.todoDescription,
done: false
});
this.todoDescription = '';
}
}
}
app.html:
<template>
<h1>Todo list</h1>
<form submit.trigger="addTodo()">
<input type="text" value.bind="todoDescription">
<button type="submit" disabled.bind="!todoDescription">Add Todo</button>
</form>
<ul>
<li repeat.for="todo of todos">
<input type="checkbox" checked.bind="todo.done">
<span css="text-decoration: ${todo.done ? 'line-through' : 'none'}">
${todo.description}
</span>
<button click.trigger="removeTodo(todo)">Remove</button>
</li>
</ul>
</template>
调试表明,分开后, todos
如何修改现有代码,以便当将新元素添加到todo列表中时,视图将相应更新?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当Aurelia看到元素时,就会创建一个Todolist的实例。当您将其“新”起来时,您已经创建了一个单独的实例。您应该使用view-model.ref捕获对Aurelia创建的实例的引用,而不是创建Todolist类的新实例。
app.html
app.ts
Aurelia creates an instance of TodoList when it sees the element. You have created a separate instance when you "newed" it up. Instead of creating a new instance of the TodoList class, you should use view-model.ref to capture a reference to the instance aurelia has created.
app.html
app.ts