Created
February 26, 2015 23:30
-
-
Save alexeyraspopov/db385133c0eeed77049c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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); | |
} | |
} | |
}; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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