Visitors are also reading...
← Previous

Don't overthink it - undirectional data flow

18 Dec 2016

Unidirectional data flow has many benefits. I am sure you already heard about them.
Here is a way you can start implementing it in a couple of minutes!
No new library, no new learning curve..

For the purpose of this post I will use Angular 1.x but it can easily translate to Angular2 and React.

2 types of components

Define 2 different types of components

Lets see an example

In the following example we have 2 angular components

// index.html === <main></main>

angular.module('app', []);

angular.module('app').component('main', {
    <div> Recently Removed: {{$ctrl.recentlyRemoved}}</div>
    <div> Recently Added: {{$ctrl.recentlyAdded}}</div>
  controller: function(){
    this.tasks = ['foo'];
    this.addTask = (task) =>{ // possible asynchronous operation! also, you can delegate to a service..
      this.recentlyAdded = task;

    this.removeTask = (index) =>{ // possible asynchronous operation! also, you can delegate to a service..
      this.recentlyRemoved = this.tasks[index];
      console.log('removing!', index)

angular.module('app').component('tasksList', {
  bindings: {
    tasks: '<',
    onAdd: '&',
    onRemove: '&'
  template: `
      <div ng-repeat="task in $ctrl.tasks track by $index">{{task}} <button ng-click="$ctrl.onRemove({index:$index})">remove</button></div>
      <input ng-model="$ctrl.newTask"/>
      <button ng-click="$ctrl.addNewTask()">Add</button>

  controller: function () {
    this.addNewTask = () => {
      console.log('adding new task!', this.newTask , this.onAdd );
      this.onAdd({ task : this.newTask });
      this.newTask = ''; // clear

Some notes:

Strengths and Improvements

So...... flux?

Could it be I just implemented a flux architecture?

Could be.. the more I learn about flux, the less I feel confident defining it.
Either way, you can definitely consider this as a step towards that direction if you wish..

My goal was to improve my code with minimal changes.

This post was inspired by

I was very inspired by this post: Don't overthink it grids!

The post that got me started on grids without fear! Another awesome post by Chris Coyer. Thanks you!

← Previous