Created
September 22, 2014 20:05
-
-
Save gilesbradshaw/658b575201b3dd828d56 to your computer and use it in GitHub Desktop.
convert rx observable to knockout observable with subscription and disposal
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
(function(){ | |
function addSubscribeDispose(observable, subscribe, dispose) { | |
var subscriptions = []; | |
var oldSubscribe = observable.subscribe.bind(observable); | |
observable.subscribe = function (callback, callbackTarget, event) { | |
var oldDispose, ret; | |
ret = oldSubscribe(callback, callbackTarget, event); | |
if (!subscriptions.length) { | |
subscribe(); | |
} | |
subscriptions.push(ret); | |
oldDispose = ret.dispose; | |
ret.dispose = function () { | |
subscriptions.splice(subscriptions.indexOf(ret), 1); | |
oldDispose.bind(this)(); | |
if (!subscriptions.length) { | |
dispose(); | |
} | |
}; | |
return ret; | |
}; | |
} | |
return function rx2koObservable(initialValue) { | |
var observable = ko.observable(initialValue); | |
var rxSubscription; | |
var _this = this; | |
addSubscribeDispose(observable,function(){ | |
rxSubscription = _this.subscribe(observable); | |
}, | |
function () { | |
return rxSubscription.dispose(); | |
}); | |
return observable; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment