Component lifecycle and immutable data

Component lifecycle - genesis

Comparison to React

How can we take advantage?

Handle changes using didReceiveAttrs

Handle jQuery using didInsertElement and willDestroy

Examples

attrsObserver: observer('value', 'value.[]', 'options.[]', function() {
  Ember.run.once(() => {
    this._handleAttrsChange();
  });
})
didReceiveAttrs() {
  this._handleAttrsChange(); 
})

Examples

Instantly Ember Run Loop compliant

Better performance

More deterministic

Examples

let options = this.get('optionsBindedToComponent');
option.pushObject(Ember.Object.create({ something: new }));

Aaaaand, we're doomed.

Immutable data

This is the reason why React favors immutable data

More deterministic

Easy to understand and follow

Allows to infer 1:1 UI / data relationship

Immutable data in Ember

Immutable arrays

let options = this.get('optionsBindedToComponent');
let newOptions = [...options, Ember.Object.create({ something: new })];
this.set('optionsBindedToComponent', newOptions);

Array destructuring (ES2015)

Immutable data in Ember

Immutable objects

let passedObject = this.get('objectBindedToComponent');
// passedObject = { something: old, otherProps... }
let newObject = Object.assign({}, passedObject, { something: new });
// newObject = { something: new, otherProps... }
this.set('optionsBindedToComponent', newOptions);

Object.assign (ES2015)

Object.assign has some drawbacks, but we skip them here

Summary

Take advantage of Ember Component lifecycle

Create more deterministic code

Stay DRY and immutable

Eventually proove Ember supremacy over React ;)

Thanks

Component lifecycle and immutable data

By Kuba Niechcial

Component lifecycle and immutable data

Previously presented on internal Netguru meetup. Short trip through component lifecycle and immutable data in Ember.js, its similarities to React and the short road to deterministic state.

  • 796