Skip to content

Instantly share code, notes, and snippets.

@alexeyraspopov
Created February 26, 2015 23:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexeyraspopov/db385133c0eeed77049c to your computer and use it in GitHub Desktop.
Save alexeyraspopov/db385133c0eeed77049c to your computer and use it in GitHub Desktop.
'use strict';
function unsubscribe(subscribers, callback){
return function(){
var index = subscribers.indexOf(callback);
if(index > -1){
subscribers.splice(index, 1);
}
};
}
function noop(){}
module.exports = function(){
var subscribers = [];
return {
subscribe: function(callback){
if(subscribers.indexOf(callback) < 0){
subscribers.unshift(callback);
return unsubscribe(subscribers, callback);
}
return noop;
},
publish: function(data){
var index = subscribers.length;
while(--index >= 0){
subscribers[index](data);
}
}
};
};
app.service('Users', function(){
return new Store({
getInitialState: function(){
return [];
},
add: function(users, name){
return users.concat({ name: name });
}
});
});
app.controller('UsersCtrl', function($scope, Users){
Users.linkTo($scope, 'users');
$scope.addUser = Users.action('add');
});
var emitter = require('./emitter');
function assign(target, source){
Object.keys(source).forEach(function(key){
target[key] = source[key];
});
}
function apply(scope, key, state){
scope.$apply(function(){
scope[key] = state;
});
}
function Store(reducers){
this.reducers = reducers;
this.state = null;
this.emitter = emitter();
}
Store.prototype.linkTo = function(scope, key){
this.emitter.subscribe(function(state){
apply(scope, key, state);
});
if(!this.state){
this.state = this.reducers.getInitialState();
}
apply(scope, key, this.state);
};
Store.prototype.action = function action(key, data){
if(arguments.length < 2){
return action.bind(this, key);
}
assign(this.state, this.reducers[key](this.state, data))
this.emitter.publish(this.state);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment