Last active
November 26, 2015 04:46
-
-
Save davinkevin/a7e5696601277f07fc1a to your computer and use it in GitHub Desktop.
AngularJS Rx replacement to $broadcast | $emit | $on
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
/** | |
* Created by kdavin on 24/11/2015. | |
*/ | |
import {Service, Module} from '../../../decorators'; | |
import Rx from 'rx'; | |
@Module({ | |
name : "app.common.services.communication" | |
}) | |
@Service("CommunicationService") | |
class CommunicationService { | |
constructor () { | |
this.subjects = new Map(); | |
} | |
$on(subject, $scope) { | |
let observable = this.$$getOrCreateSubject(subject); | |
$scope.$on(subject, (_, data) => observable.onNext(data)); | |
return this.$sub(subject, $scope, true); | |
} | |
$sub(subject, $scope, needApply = false) { | |
return { | |
$do : (func) => { | |
let subscriber = needApply ? (data) => $scope.$apply(() => func(data)) : data => func(data); | |
let dispose = this.$$getOrCreateSubject(subject).subscribe(subscriber); | |
this.$$declareDestruction ($scope, dispose); | |
} | |
}; | |
} | |
$$declareDestruction($scope, dispose) { | |
$scope.$on ('$destroy', () => { | |
dispose.dispose (); | |
this.$$removeUnusedTopic(); | |
}); | |
} | |
$emit(subject) { | |
return { | |
$send : (val) => this.$$getOrCreateSubject(subject).onNext(val) | |
}; | |
} | |
$$getOrCreateSubject(subject) { | |
this.subjects.has(subject) ? this.subjects.get(subject) : this.subjects.set(subject, new Rx.ReplaySubject(0)); | |
return this.subjects.get(subject); | |
} | |
$$removeUnusedTopic() { | |
this.subjects.forEach((value, key, map) => { | |
if (!value.hasObservers()) | |
map.delete(key); | |
}); | |
} | |
} | |
export default CommunicationService; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment