Last active
November 1, 2015 21:01
-
-
Save adhamankar/fadede965a9a6de2ceae to your computer and use it in GitHub Desktop.
TypeScript+ Angular DataService based on observer pattern
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
module CommonServices { | |
export class DataService<T> { | |
public data: T; | |
private observerCallbacks = []; // Observer pattern implementation | |
public registerCallback = (callback) => { | |
this.observerCallbacks.push(callback); | |
}; | |
public setData = (instance: T) => { | |
this.data = instance; | |
angular.forEach(this.observerCallbacks,(callback?: Function) => callback()); | |
}; | |
public getData = (): T => { | |
return this.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
module Projects { | |
"use strict"; | |
export class IterationDataService extends CommonServices.DataService<Iteration> { | |
public static Factory() { | |
return new IterationDataService(); | |
} | |
} | |
} | |
//registration as data service | |
angular.module("projects", []) | |
.factory("IterationDataService", Projects.IterationDataService.Factory) | |
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
module Projects { | |
"use strict"; | |
export class IterationDetailsCtrl { | |
public static $inject = ["$scope", "$http", "$state", "IterationDataService"]; | |
constructor(public $scope: ng.IScope | |
, public $http: ng.IHttpService | |
, public $state: ng.ui.IStateService | |
, public IterationDataService: IterationDataService | |
) { | |
super($scope); | |
var me = this; | |
//setting data | |
$http.get(me.getUrl()) | |
.success((data: Iteration) => { | |
me.iteration = data; | |
me.IterationDataService.setData(me.iteration); | |
}); | |
//getting data | |
this.IterationDataService.registerCallback(() => { | |
me.iteration = this.IterationDataService.getData(); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment