Last active
September 9, 2016 06:21
-
-
Save dagstuan/0a49e60135abb9861c758b18b1fdf00e to your computer and use it in GitHub Desktop.
selectAndSubscribe-decorator for ng2-redux
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
import { NgRedux } from 'ng2-redux'; | |
import { ISubscription } from 'rxjs/Subscription'; | |
export const selectAndSubscribe = <T>( | |
statePathOrFunc?: string | | |
(string | number)[] | | |
Function, | |
comparer?: (x: any, y: any) => boolean) => (target, key) => { | |
let bindingKey = statePathOrFunc; | |
if (!statePathOrFunc) { | |
bindingKey = (key.lastIndexOf('$') === key.length - 1) ? | |
key.substring(0, key.length - 1) : | |
key; | |
} | |
let val: any; | |
let subscription: ISubscription; | |
function getter() { | |
if(!subscription) { | |
subscription = | |
NgRedux.instance | |
.select(bindingKey, comparer) | |
.subscribe(newVal => val = newVal); | |
} | |
return val; | |
} | |
// Delete property. | |
if (delete this[key]) { | |
// Create new property with getter and setter | |
Object.defineProperty(target, key, { | |
get: getter, | |
enumerable: true, | |
configurable: true | |
}); | |
} | |
if(delete this['ngOnDestroy']) { | |
let onDestroy = | |
target.ngOnDestroy ? target.ngOnDestroy : () => undefined; | |
let newOnDestroy = function() { | |
if (subscription) { | |
subscription.unsubscribe(); | |
subscription = undefined; | |
} | |
onDestroy.bind(this)(); | |
} | |
Object.defineProperty(target, 'ngOnDestroy', { | |
value: newOnDestroy | |
}); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment