peerlibrary:reactive-field

v0.6.0Published 5 years ago

This package has not had recent updates. Please investigate it's current state before committing to using it in your project.

Reactive field for Meteor

Reactive field for Meteor provides an alternative syntax for ReactiveVar:

1var field = new ReactiveField('initialValue');
2console.log(field()); // prints 'initialValue' string
3field('newValue');
4console.log(field()); // prints 'newValue' string

So instead of field.get() and field.set(), you can simply call it as a function which (reactively) returns a value, or call it with an argument to set the new value. Setter still returns the value.

Optionally, you can pass custom equality function:

1new ReactiveField('initialValue', function (a, b) {return a === b});

You can also enable storing the previous value stored in the reactive field using:

1// You can also pass it as a third argument when using custom equality function
2var field = new ReactiveField('initialValue', true);
3console.log(field()); // prints 'initialValue' string
4field('newValue');
5console.log(field()); // prints 'newValue' string
6console.log(field.previous()); // prints 'initialValue' string

This is useful when you want to compare inside a computation how the value changed. field.previous() is not reactive.

Adding this package to your Meteor application adds the ReactiveField constructor into the global scope.

Both client and server side.

Installation

meteor add peerlibrary:reactive-field

Motivation

The main motivation for this package is that you can assign reactive values to Blaze Components and then you can access them in the template by simply doing {{field}} instead of {{field.get}}. And same for any other objects for which you create reactive fields in the constructor and then you or have this.field.get() calls all around the code, which is ugly because if you ever decide to convert this.field into a getter with some additional logic you have to change code everywhere. Or you create a this.field() getter in advance, which calls this._field.get() for you, but that is again a lot of work. So the easiest thing is to have reactive fields be methods to begin with so you can change them later on if necessary while keeping backwards compatibility.

  • reactive-var – the official Meteor reactive variable implementation

which this package just wraps, so the functionality is the same, just syntax how to use it is different

package