cellx

The ultra-fast implementation of reactivity for javascript

README

Этот документ на русском



Ultra-fast implementation of reactivity for javascript.

NPM version
Build Status
Coverage Status

Installation


The following command installs cellx as a npm package:
  1. ```
  2. npm install cellx --save
  3. ```

Example


  1. ```js
  2. let user = {
  3.     firstName: cellx('Matroskin'),
  4.     lastName: cellx('Cat'),

  5.     fullName: cellx(function() {
  6.         return (user.firstName() + ' ' + user.lastName()).trim();
  7.     })
  8. };

  9. user.fullName.subscribe(function() {
  10.     console.log('fullName: ' + user.fullName());
  11. });

  12. console.log(user.fullName());
  13. // => 'Matroskin Cat'

  14. user.firstName('Sharik');
  15. user.lastName('Dog');
  16. // => 'fullName: Sharik Dog'
  17. ```

Despite the fact that the two dependencies of the cell fullName has been changed, event handler worked only once.
Important feature of cellx is that it tries to get rid of unnecessary calls
of the event handlers as well as of unnecessary calls of the dependent cells calculation formulas.
In combination with some special optimizations, this leads to an ideal speed of calculation of
the complex dependencies networks.

Benchmark


One test, which is used for measuring the performance, generates grid with multiply "layers"
each of which is composed of 4 cells. Cells are calculated from the previous layer of cells (except the first one,
which contains initial values) by the formula A2=B1, B2=A1-C1, C2=B1+D1, D2=C1. After that start time is stored,
values of all first layer cells are changed and time needed to update all last layer cells is measured.
Test results (in milliseconds) for different number of layers (for Google Chrome 53.0.2785.116 (64-bit)):

Library1020305010010005000
|---|---|---|---|---|---|---|---|
cellx<~1<~1<~1<~1<~1420
VanillaJS<~1151750>300000>300000>300000>300000
[Knockout](http://knockoutjs.com/)10750,67250,>300000>300000>300000>300000
[$jin.atom](https://github.com/nin-jin/pms-jin/)2334640230
[$mol_atom](https://github.com/nin-jin/mol)<~1<~1<~11220RangeError:
[Reactor.js](https://github.com/fynyky/reactor.js)<~1<~123550230
[Reactive.js](https://github.com/mattbaker/Reactive.js)<~1<~1235140RangeError:
[Kefir.js](https://rpominov.github.io/kefir/)252500>300000>300000>300000>300000>300000
[MobX](https://mobxjs.github.io/mobx/)<~1<~1<~12340RangeError:

Test sources can be found in the folder perf.
Density of connections in real applications is usually lower than in the present test, that is,
if a certain delay in the test is visible in 100 calculated cells (25 layers), in a real application,
this delay will either be visible in the greater number of cells, or cells formulas will include
some complex calculations (e.g., computation of one array from other).

Usage


Cells can be stored in the variables:

  1. ```js
  2. let num = cellx(1);
  3. let plusOne = cellx(() => num() + 1);

  4. console.log(plusOne());
  5. // => 2
  6. ```

or in the callable properties:

  1. ```js
  2. function User(name) {
  3.     this.name = cellx(name);
  4.     this.nameInitial = cellx(() => this.name().charAt(0).toUpperCase());
  5. }

  6. let user = new User('Matroskin');

  7. console.log(user.nameInitial());
  8. // => 'M'
  9. ```

or in simple properties:

  1. ```js
  2. function User(name) {
  3.     cellx.define(this, {
  4.         name: name,
  5.         nameInitial: function() { return this.name.charAt(0).toUpperCase(); }
  6.     });
  7. }

  8. let user = new User('Matroskin');

  9. console.log(user.nameInitial);
  10. // => 'M'
  11. ```

Usage with ES.Next


Use npm module cellx-decorators.

Usage with React


Use npm module cellx-react.

More modules for cellx



Options


When you create a cell, you can pass some options:

get


Additional processing of value during reading:

  1. ```js
  2. // array that you can't mess up accidentally, the messed up thing will be a copy
  3. let arr = cellx([1, 2, 3], {
  4.     get: arr => arr.slice()
  5. });

  6. console.log(arr()[0]);
  7. // => 1

  8. arr()[0] = 5;

  9. console.log(arr()[0]);
  10. // => 1
  11. ```

put


Used to create recordable calculated cells:

  1. ```js
  2. function User() {
  3.     this.firstName = cellx('');
  4.     this.lastName = cellx('');

  5.     this.fullName = cellx(
  6.   () => (this.firstName() + ' ' + this.lastName()).trim(),
  7.   {
  8.    put: name => {
  9.     name = name.split(' ');

  10.     this.firstName(name[0]);
  11.     this.lastName(name[1]);
  12.    }
  13.   }
  14. );
  15. }

  16. let user = new User();

  17. user.fullName('Matroskin Cat');

  18. console.log(user.firstName());
  19. // => 'Matroskin'
  20. console.log(user.lastName());
  21. // => 'Cat'
  22. ```

validate


Validates the value during recording and calculating.

Validation during recording into the cell:

  1. ```js
  2. let num = cellx(5, {
  3.     validate: value => {
  4.         if (typeof value != 'number') {
  5.             throw new TypeError('Oops!');
  6.         }
  7.     }
  8. });

  9. try {
  10.     num('I string');
  11. } catch (err) {
  12.     console.log(err.message);
  13.     // => 'Oops!'
  14. }

  15. console.log(num());
  16. // => 5
  17. ```

Validation during the calculation of the cell:

  1. ```js
  2. let value = cellx(5);

  3. let num = cellx(() => value(), {
  4.     validate: value => {
  5.         if (typeof value != 'number') {
  6.             throw new TypeError('Oops!');
  7.         }
  8.     }
  9. });

  10. num.subscribe(err => {
  11.     console.log(err.message);
  12. });

  13. value('I string');
  14. // => 'Oops!'

  15. console.log(value());
  16. // => 'I string'

  17. console.log(num());
  18. // => 5
  19. ```

Methods


onChange


Adds a change listener:

  1. ```js
  2. let num = cellx(5);

  3. num.onChange(evt => {
  4.     console.log(evt);
  5. });

  6. num(10);
  7. // => { prevValue: 5, value: 10 }
  8. ```

offChange


Removes previously added change listener.

onError


Adds a error listener:

  1. ```js
  2. let value = cellx(1);

  3. let num = cellx(() => value(), {
  4.     validate: v => {
  5.         if (v > 1) {
  6.             throw new RangeError('Oops!');
  7.         }
  8.     }
  9. });

  10. num.onError(evt => {
  11.     console.log(evt.error.message);
  12. });

  13. value(2);
  14. // => 'Oops!'
  15. ```

offError


Removes previously added error listener.

subscribe


Subscribes to the events change and error. First argument comes into handler is an error object, second — an event.

  1. ```js
  2. user.fullName.subscribe((err, evt) => {
  3.     if (err) {
  4.         //
  5.     } else {
  6.         //
  7.     }
  8. });
  9. ```

unsubscribe


Unsubscribes from events change and error.

Subscription to the properties created with help cellx.define


Subscribe to changes in the properties created with help of cellx.define possible through EventEmitter:

  1. ```js
  2. class User extends cellx.EventEmitter {
  3.     constructor(name) {
  4.         cellx.define(this, {
  5.             name,
  6.             nameInitial: function() { return this.name.charAt(0).toUpperCase(); }
  7.         });
  8.     }
  9. }

  10. let user = new User('Matroskin');

  11. user.on('change:nameInitial', evt => {
  12.     console.log('nameInitial: ' + evt.value);
  13. });

  14. console.log(user.nameInitial);
  15. // => 'M'

  16. user.name = 'Sharik';
  17. // => 'nameInitial: S'
  18. ```

dispose


In many reactivity engines calculated cell (atom, observable-property) should be seen
as a normal event handler for other cells, that is, for "killing" the cell it is not enough to simply remove
all handlers from it and lose the link to it, it is also necessary to decouple it from its dependencies.
Calculated cells in cellx constantly monitor the presence of handlers for themselves and all their descendants,
and in cases of their (handlers) absence went to the passive updates mode, i.e. unsubscribe themselves from their
dependencies and are evaluated immediately upon reading. Thus, to "kill" of the cell you just calculated
remove from it all handlers added before and forget the link to it; you do not need to think about the other cells,
from which it is calculated or which are calculated from it. After this, garbage collector will clean everything.

You can call the dispose, just in case:

  1. ```js
  2. user.name.dispose();
  3. ```

This will remove all the handlers, not only from the cell itself, but also from all cells calculated from it,
and in the absence of links all branch of dependencies will "die".

Dynamic actualisation of dependencies


Calculated cell formula can be written so that a set of dependencies may change over time. For example:

  1. ```js
  2. let user = {
  3.     firstName: cellx(''),
  4.     lastName: cellx(''),

  5.     name: cellx(() => {
  6.         return this.firstName() || this.lastName();
  7.     })
  8. };
  9. ```

There, while firstName is still empty string, cell name is signed for firstName and lastName,
and change in any of them will lead to the change in its value. If you assign to the firstName some not empty
string, then during recalculation of value name it simply will not come to reading lastName in the formula,
i.e. the value of the cell name from this moment will not depend on lastName.
In such cases, cells automatically unsubscribe from dependencies insignificant for them and are not recalculated
when they change. In the future, if the firstName again become an empty string, the cell name will re-subscribe
to the lastName.

Synchronization of value with synchronous storage


  1. ```js
  2. let foo = cellx(() => localStorage.foo || 'foo', {
  3. put: function(cell, value) {
  4.   localStorage.foo = value;
  5.   cell.push(value);
  6. }
  7. });

  8. let foobar = cellx(() => foo() + 'bar');

  9. console.log(foobar()); // => 'foobar'
  10. console.log(localStorage.foo); // => undefined
  11. foo('FOO');
  12. console.log(foobar()); // => 'FOObar'
  13. console.log(localStorage.foo); // => 'FOO'
  14. ```

Synchronization of value with asynchronous storage


  1. ```js
  2. let request = (() => {
  3. let value = 1;

  4. return {
  5.   get: url => new Promise((resolve, reject) => {
  6.             setTimeout(() => {
  7.                 resolve({
  8.                     ok: true,
  9.                     value
  10.                 });
  11.             }, 1000);
  12.         }),

  13.   put: (url, params) => new Promise((resolve, reject) => {
  14.             setTimeout(() => {
  15.                 value = params.value;

  16.                 resolve({
  17.                     ok: true
  18.                 });
  19.             }, 1000);
  20.         })
  21. };
  22. })();

  23. let foo = cellx(function(cell, next = 0) {
  24. request.get('http://...').then((res) => {
  25.   if (res.ok) {
  26.    cell.push(res.value);
  27.   } else {
  28.    cell.fail(res.error);
  29.   }
  30. });

  31. return next;
  32. }, {
  33. put: (value, cell, next) => {
  34.   request.put('http://...', { value: value }).then(res => {
  35.    if (res.ok) {
  36.     cell.push(value);
  37.    } else {
  38.     cell.fail(res.error);
  39.    }
  40.   });
  41. }
  42. });

  43. foo.subscribe(() => {
  44. console.log('New foo value: ' + foo());
  45. foo(5);
  46. });

  47. console.log(foo());
  48. // => 0

  49. foo('then', () => {
  50.     console.log(foo());
  51. });
  52. // => 'New foo value: 1'
  53. // => 1
  54. // => 'New foo value: 5'
  55. ```

List of references