lai:reactive-number

v2.0.1Published 10 years ago

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

ReactiveNumber

Manipulate and fetch a number reactively.

Installation

meteor add lai:reactive-number

Why?

Because I'm sick and tired of doing:

1Session.set('counter', Session.get('counter')++);
2// and
3number.set(number.get()++);

Usage

This is the initial Meteor counter app, but using ReactiveNumber instead of Session.

1if (Meteor.isClient) {
2  // counter starts at 0
3  var counter = new ReactiveNumber(0);
4
5  Template.hello.helpers({
6    counter: function () {
7      return counter.get();
8    }
9  });
10
11  Template.hello.events({
12    'click button': function () {
13      counter.add(1);
14    }
15  });
16}

Here's all the use cases.

1var number = new ReactiveNumber(1);
2number.add(1) // 2
3number.subtract(12); // -10
4number.multiply(-10); // 100
5number.divide(4); // 25
6number.calculate(function (number) {
7  return Math.sqrt(number); // 5
8});

You can also chain your calls (v2.0):

1var number = new ReactiveNumber(1);
2number
3  .add(1) // 2
4  .subtract(12); // -10
5  .multiply(-10); // 100
6  .divide(4); // 25
7  .calculate(function (number) {
8    return Math.sqrt(number); // 5
9  });

You can use most of the Math functions (v2.0):

1var number = new ReactiveNumber(100);
2number
3  // You don't have to pass an argument for all the
4  // single-argument Math functions
5  .sqrt(); // 10
6  // For the Math functions that take two arguments
7  // you only need to pass the second argument, the
8  // first argument is implicit
9  .pow(2); // 100
10  // For the Math.min and Math.max functions which take
11  // any number of arguments, the current value of the reactive
12  // number is included in the list of arguments and will set
13  // the min (or max) value as the new value
14  .min(400, 1, 20) // 1

API

new ReactiveNumber(Number);

Instantiates a reactive number. Floats allowed. NaNs not allowed. An initial argument is required.

.get()

Returns the value of the number reactively. You can call this at the end of a chaining sequence to get your value.

.set()

Sets the value of the number and triggers reactivity. The following methods set the value as well.

.add(Number)

.subtract(Number)

.multiply(Number)

.divide(Number)

.calculate(Function)

Need something more elaborate? To create a custom calculation, pass in a function with the parameter as the current value of the ReactiveNumber.

Math functions

All non-experimental Math functions are included, except for Math.atan2(y, x) and Math.random(), since they don't make much sense to include in this package.

Warning

Do not do a calculative chaining sequence inside a Template helper or anywhere with dependency tracking (Tracker.autorun()), otherwise you will get stuck in an infinite loop.