Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions bibimbap.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
'use strict';

var emitter = require('component-emitter');
var assign = require('object-assign');
var flatten = require('array-flatten');
var isPlainObject = require('is-plain-object');
Expand All @@ -12,10 +11,37 @@ module.exports = Bibimbap;
*/
function Bibimbap(tree) {
if (!(this instanceof Bibimbap)) return new Bibimbap(tree);
emitter(this);
this.tree = tree;
this.listeners = [];
}

/**
* Subscribe to state changes
*/
Bibimbap.prototype.subscribe = function(listener) {
this.listeners.push(listener);
var isSubscribed = true;

return function unsubscribe() {
if (!isSubscribed) {
return;
}

isSubscribed = false;
var index = this.listeners.indexOf(listener);
this.listeners.splice(index, 1);
}
};

/**
* Publish a state change
*/
Bibimbap.prototype.publishCommit = function(tree, prev, cursor) {
this.listeners.slice().forEach(function(listener) {
listener(tree, prev, cursor);
});
};

/**
* Commit a cursor
*/
Expand All @@ -29,7 +55,7 @@ Bibimbap.prototype.commit = function(cursor) {
// applied to the tree
cursor.operations = [];

this.emit('commit', this.tree, prev, cursor);
this.publishCommit(this.tree, prev, cursor);
};

function runOperations(tree, operations) {
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
"author": "",
"license": "MIT",
"dependencies": {
"component-emitter": "^1.2.0",
"array-flatten": "^2.0.0",
"object-assign": "^4.0.1",
"is-plain-object": "^2.0.1"
Expand Down
4 changes: 2 additions & 2 deletions test/bibimbap.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ describe('Bibimbap', function() {
var state = new Bibimbap({
test: 'original'
});
state.on('commit', function(tree, prev, cursor) {
state.subscribe(function(tree, prev, cursor) {
assert.equal('hello', tree.test);
assert.equal('hello', cursor.get());
assert.equal('original', prev.test);
Expand All @@ -156,7 +156,7 @@ describe('Bibimbap', function() {
var state = new Bibimbap({
test: 'original'
});
state.on('commit', function(tree, prev, cursor) {
state.subscribe(function(tree, prev, cursor) {
assert.equal('second', tree.test);
assert.equal('second', cursor.get());
assert.equal('original', prev.test);
Expand Down