Skip to content

Instantly share code, notes, and snippets.

@abriening
Created March 24, 2017 13:16
Show Gist options
  • Save abriening/9d3cda6d203683e2897687316f1ed5b1 to your computer and use it in GitHub Desktop.
Save abriening/9d3cda6d203683e2897687316f1ed5b1 to your computer and use it in GitHub Desktop.
function observer(){
var observers = [];
return {notify: notify, subscribe:subscribe}
function subscribe(callback){
observers.push(callback);
var i = observers.length - 1;
return function(){
observers[i] = function(){}
}
}
function notify(msg){
setTimeout(function(){
for(var i=0; i < observers.length; i++){
try{
observers[i](msg);
}catch(e){
//
}
}
});
}
}
function getService($http){
var cache = {};
return function(id){
return cache[id] = cache[id] || buildService(id);
}
function buildService(id){
var d,n,o = observer(), e = observer();
return {subscribe:subscribe, error:error, reload:reload};
function setup(){
p = p || $http.get("/data/"+id).then(function(r){
o.notify(r.data);
d = r.data;
}, e.notify);
}
function reload(){
d = p = null;
setup();
}
function subscribe(callback){
o.subscribe(callback);
if(d){
callback(d);
}
setup()
}
function error(callback){
o.subscribe(callback);
}
}
}
function putService($http){
return {put:put};
function put(data){
return $http.put("/data", data);
}
}
function controller(getService, putService){
var service = getService(1)
var ctrl = {data:{}, errors:[]};
ctrl.$onInit = function(){
service.subscribe(function(d){
ctrl.data = d;
})
service.error(function(e){
ctrl.errors.push(e);
})
}
ctrl.put = function(data){
putService.put(data).then(function(){
getService(data.Id).reload();
});
}
return ctrl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment