Socket
Socket
Sign inDemoInstall

reactivity

Package Overview
Dependencies
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

reactivity - npm Package Compare versions

Comparing version 0.0.0 to 1.0.0

lib/Base.js

81

lib/core.js
// Generated by CoffeeScript 1.6.3
(function() {
var Evaluation;
Evaluation = require('./Evaluation');
module.exports = function() {
var Evaluation, Result, active, construct_notifier, get_current, notifier, run, stack;
var active, notifier, run, stack;
stack = [];
get_current = function() {
return stack[stack.length - 1];
};
construct_notifier = function() {
var fired, listeners;
fired = false;
listeners = null;
return {
notify: function() {
var c, listener, _i, _len;
if (!fired) {
fired = true;
}
for (_i = 0, _len = listeners.length; _i < _len; _i++) {
c = listeners[_i];
c();
}
return listener = null;
},
"public": {
fired: function() {
return fired;
},
notify: function(f) {
return (listeners != null ? listeners : listeners = []).push(f);
}
}
};
};
Result = (function() {
function Result(_arg) {
this.error = _arg.error, this.result = _arg.result, this.notifier = _arg.notifier;
}
return Result;
})();
Evaluation = (function() {
function Evaluation(func) {
this.func = func;
this.n = void 0;
}
Evaluation.prototype.run = function() {
var e, _ref, _ref1;
try {
return new Result({
result: this.func(),
notifier: (_ref = this.n) != null ? _ref["public"] : void 0
});
} catch (_error) {
e = _error;
return new Result({
error: e,
notifier: (_ref1 = this.n) != null ? _ref1["public"] : void 0
});
} finally {
delete this.func;
delete this.n;
}
};
Evaluation.prototype.notifier = function() {
return (function(n) {
return function() {
return n.notify();
};
})(this.n != null ? this.n : this.n = construct_notifier());
};
return Evaluation;
})();
run = function(f) {

@@ -90,3 +21,3 @@ var ev;

var _ref;
return (_ref = get_current()) != null ? _ref.notifier() : void 0;
return (_ref = stack[stack.length - 1]) != null ? _ref.notifier() : void 0;
};

@@ -93,0 +24,0 @@ active = function() {

// Generated by CoffeeScript 1.6.3
(function() {
var build, core, util, _base;
var build, core, _base, _poll, _subscribe;
core = require('./core');
util = require('./util');
_poll = require('./poll');
_subscribe = require('./subscribe');
/*
Main entry point to the reactivity framework.
Exports an object that exposes the 5 API methods.
The object is itself an overloaded function that proxies
to the methods for convenience.
*/
build = function() {
var active, main, notifier, poll, run, subscribe, _ref, _ref1;
_ref = core(), notifier = _ref.notifier, active = _ref.active, run = _ref.run;
_ref1 = util(), subscribe = _ref1.subscribe, poll = _ref1.poll;
/*
m() = notifier()
m( func ) = run(func)
m( func, func ) = subscribe( func, func )
m( func, interval ) = poll( func, interval )
# more convenient
m( interval, func ) = poll( func, interval )
*/
var active, main, notifier, poll, run, subscribe, _c, _ref;
_ref = _c = core(), notifier = _ref.notifier, active = _ref.active, run = _ref.run;
subscribe = _subscribe(_c);
poll = _poll(_c);
main = function(x, y) {

@@ -50,4 +48,4 @@ switch (typeof x + ' ' + typeof y) {

module.exports = (_base = global || window).NR != null ? (_base = global || window).NR : _base.NR = build();
module.exports = (_base = global || window).reactivity != null ? (_base = global || window).reactivity : _base.reactivity = build();
}).call(this);
{
"name": "reactivity",
"version": "0.0.0",
"version": "1.0.0",
"description": "Native Reactivity for Javascript",
"author": "Aldo Bucchi <aldo.bucchi@gmail.com>",

@@ -17,3 +18,10 @@ "main": "lib",

"coffee-script": "~1.6.3"
},
"repository": {
"type": "git",
"url": "https://github.com/aldonline/reactivity.js.git"
},
"bugs": {
"url": "https://github.com/aldonline/reactivity.js/issues"
}
}

@@ -1,13 +0,13 @@

# Native Reactivity for Javascript
# Reactivity.io
##The Native Reactivity Standard for Javascript
![Native Reactivity for Javascript logo](https://raw.github.com/aldonline/njsr/master/etc/nrjs-250.png)
*Native Reactivity* is a very simple "hack" that allows native functions and expressions in Javascript
to become Reactive. Which is a fancy way of saying that **they can notify consumers when their result changes**.
Native Reactivity for Javascript ( aka NR.js ) is a micro-library that allows native functions and expressions in Javascript
to become Natively Reactive. Which is a fancy way of saying that they can notify other functions their return value changes.
Using *Native* Reactivity gives you one very important feature for free:
Changes are propagated transparently up the call stack. Native Reactivity is automatically transitive - any function that depends on a reactive function is reactive itself.
The technique is so simple that it "blends into" the language. There is no need to create
"Observable" objects, Event Emitters or evaluate expressions in a sublanguage.
Any Javascript function can be Natively Reactive. And any function that depends on a Natively Reactive function becomes Natively Reactive automatically.
This means that there is no need to explicitly declare dependencies.
There is no need to explicitly define dependency relations between functions.
The only "catch" is that everyone has to use the **same** implementation. This is the reason behind the reactivity.io effort. It defines an API and provides a cannonical implementation.

@@ -18,8 +18,8 @@ # Installation

Install via NPM
```shell
npm install reactivity
```
npm install nr
```javascript
var NR = require('nr')
var reactivity = require('reactivity')
```

@@ -32,9 +32,14 @@

```html
<script src="https://raw.github.com/aldonline/nrjs/master/dist/nr.min.js"></script>
<script src="https://raw.github.com/aldonline/reactivity.js/master/dist/reactivity.min.js"></script>
```
The global NR object is attached to the root scope ( window )
In the browser, the global reactivity object is attached to the root scope ( window )
var NR = window.NR
```javascript
var reactivity = window.reactivity
```
If the object is already present then the library won't mess things up.
It will proxy calls to the pre-existing implementation.
# Overview

@@ -44,3 +49,3 @@

Functions throw an invalidation event up the stack.
Functions throw an *invalidation event* up the stack.
However, because the stack is transient and won't exist in the future, functions

@@ -50,5 +55,8 @@ that wish to notify a change need to request a callback so they can

Requesting this callback will make sure that any consuming functions get a chance to ask for notifiers
on the other side.
```javascript
function time(){
var notifier = NR() // request a notifier
var notifier = reactivity.notifier() // request a notifier
setTimeout( notifier, 1000 ) // call it in 1000MS

@@ -59,3 +67,3 @@ return new Date().getTime()

The caller of the function, on the other hand, will have an opportunity to register
The caller of the function will have an opportunity to register
a listener to be notified when any of the functions that participated in the evaluation are invalidated.

@@ -66,13 +74,153 @@ At this point you can decide to re-evaluate the expression.

```javascript
var r = NR( time ) // run the function in a native reactive context
// run the function in a reactive context
// instead of returning the result or throwing an error
// it will return an object with three properties: result, error and monitor
var r = reactivity.run( time )
// we are interested in the result
var time = r.result
var notifier = r.notifier
if ( notifier != null ){ // at least one notifier was registered downstream
notifier.add( function(){
// and the monitor
var monitor = r.monitor
// the monitor is null unless the function is reactive
// ( or depends on a reactive function - reactivity is transitive )
// in this case we know that time() is reactive since we created it ourselves
// but we still check for illustrative purposes
if ( monitor != null ){
// and we can now wait to be notifier of a change
monitor.onChange( function(){
console.log( "we should reevaluate the expression" )
})
}
})
}
```
# API
There are two different APIs. One for each side of the problem ( consuming VS publishing )
signature | shortcut | description
--- | --- | ---
reactivity.run( f:Function ):Result | reactivity(f) | runs code in a reactive context
Result::result | x | x
Result::error | x | x
## Consumer Side
### reactivity.run( reactiveFunction : Function ):Result
Runs a reactive function and returns a *Result* object
Shortcut:
```javascript
reactivity(func)
```
### reactivity.subscribe( reactiveFunction:Function )
Runs a reactive function repeatedly.
Shortcut:
```javascript
reactivity( reactiveFunction, callback )
// example
reactivity( reactiveFunction, function(error, result, monitor){
// ...
})
```
### reactivity.poll( reactiveFunc : Function, interval : Number ):Function
Transform any function into a reactive function by repeatedly evaluating it and
comparing its result.
Using this method is considered bad practice in general.
```javascript
var reactiveFunc = reactivity.poll( func, 500 )
```
Shortcut:
```javascript
reactivity( func, 500 )
```
## Result Object
The Result object has three properties:
* result
* error
* monitor
## Monitor Object
### monitor.state():String
states: ready, changed, destroyed, cancelled
### monitor.onChange( handler : Function )
Registers a callback that will be called whenever the monitored function changes.
### monitor.onCancel( handler : Function )
### monitor.destroy( )
## Producer API
### reactivity.notifier( ):Notifier
Returns a Notifier
Shortcut:
```javascript
reactivity()
```
### reactivity.active():Boolean
## Notifier
### notifier.fire()
Shortcut
```javascript
notifier()
```
### notifier.destroy()
### notifier.state():String
States: ready, cancelled, fired, destroyed
### notifier.onCancel( handler:Function )
# Advanced
## Creating a Reactive function
## Consuming a Reactive function
# FAQ

@@ -86,9 +234,9 @@

This means ( at the least ) sharing a global object where invalidators and notifiers meet each other.
NR.js provides a microlibrary and a set of conventions.
reactivity.js provides a microlibrary and a set of conventions.
If we all follow them, Javascript automatically becomes a MUCH more powerful language.
## Why does't the Invalidation event provide me with a way to inspect previous and current values?
## Why does't the Notifier provide me with a way to inspect previous and current values?
Because an expression may depende on several reactive functions,
the Invalidation event you catch on the top of the stack may come from any of them.
Because an expression may depend on several reactive functions,
the Invalidation event you catch at the top of the stack may come from any of them.
The value of this specific function is not important.

@@ -99,8 +247,16 @@ What's important is the result of evaluating the complete expression.

Like all good ideas and patterns in software they have been discoverd and rediscovered over and over again by venturous programmers. The author of this library can attest that its first encounter with this pattern was as part of a strategy to invalidate caches when calling complex stored procedures probably 15 years ago. The implementation details were a bit different but the principle was the same. Naturally, this idea was ported to Javascript over a decade ago.
Like all good ideas and patterns in software they have been discovered and rediscovered over and over again. The author of this library can attest that its first encounter with this pattern was as part of a strategy to invalidate caches when calling complex stored procedures probably 15 years ago. The implementation details were a bit different but the principle was the same. Naturally, this idea was ported to Javascript over a decade ago.
Lately it has popped up in several places. The most notable of them all is probably the Meteor.js framework, where it is tightly coupled with the framework.
Just search for "reactive" on NPM.
## Why doesn't the module use classic EventEmitters?
* Adding an event emitter implementation adds significant overhead.
* It increments contact surface
* There is more than one event emitter API style ( DOM vs Node, for example )
* The places where you register notifiers are usually very locally scoped ( right after an evaluation for example ) and adding more than one listener is not a common use case.
* You can always build a more complex subscription model on top
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc