神刀安全网

Ember and Data Down, Actions Up

When I first started with Ember.js, two-way data binding was exciting because it removed a lot of the manual work around keeping templates/components up to date with data being presented. Two-way data binding allowed changes to models to be automatically reflected in the UI, and changes in the UI to reflect back up to the model layer.

However, this approach led to some difficulties. Larger applications with data flow in all directions became hard to reason about. In addtion, many experienced issues with data becoming out of sync. To address this, Ember 2.X is working toward disabling two-way data binding by default, and recommends the “data down, actions up” (DDAU) pattern for managing data flow. So what does this look like?

Data Down. Data should only be mutated/persisted by a top-level component or controller, which will cause the template/child components to be re-rendered, or send data down.

Actions Up. When a change is made to data in the UI, an action should be sent up the hierarchy to notify the parent component/controller to persist the change.

Example

I’ll use the classic todo app to demostrate an example of data down, actions up. ( I’ll also use a controller as routable components are currenly in development )

The todos controller will own the data, or the todos collection, and be responsible for making and changes to the collection.

// app/routes/todos.js export default Ember.Route.extend({   // ...    setupController(controller, model) {     controller.set('todos', model);   } });

The todo template will render a list of todo components, and display a completion ratio component.

// app/templates/todos.emblem completed-todo-ratio todos=todos  each todos as |todo|   todo-card todo=todo todoCompleted=(action 'completeTodo')

When a todo is marked as complete by click, the todo-card component will call the completeTodo action passed to it to notify the controller of the change.

// app/components/todo-card.js export default Ember.Component.extend({   click() {     const todo = this.get('todo');     this.attrs.todoCompleted(todo);   } });

Before DDAU, it would have been acceptable to save the todo from within the todo-card component. Instead, the todos controller will save the todo as completed, causing the template and components to be re-rendered to reflect the change.

// app/controllers/todos.js export default Ember.Controller.extend({   actions: {     completeTodo(todo) {       todo.set('isComplete', true);       todo.save();     },      // ... });

Following the DDAU pattern adds structure to the flow of data in an application. Give it a shot!

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Ember and Data Down, Actions Up

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮