-
-
Save luggage66/3dcbb0dc3e4fd2cf8e1470b8c634c19b to your computer and use it in GitHub Desktop.
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 ko from 'ko'; | |
// a simple extension to return false UNTIL fn() returns a truthy value. | |
// As soon as it does we stop. | |
// To start again, just set THIS observable to false and it'll re-check and re-subscribe. | |
// This means it'll check once on creation and once each time we get any notifications of | |
// changes until fn() is true (which will likely be the first notification). | |
// Then no more until we set false and it'll check once to get started (just like at creation) | |
function observeUntilTrue(fn) { | |
//when called on an existing observable (as an extension), use that. otherwise make our own. | |
var flag = this || ko.observable(false); | |
// just run the original function with a short-circuit. | |
return ko.computed(() => { | |
return (flag() || fn()); | |
}); | |
} | |
// register as a ko extension. if done once, it'll be available on ALL observables. | |
ko.subscribable.fn.observeUntilTrue = observeUntilTrue; | |
//also export this so we can use it as a function. | |
export default observeUntilTrue; //so you can use it as a module. |
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 ko from 'ko'; | |
import observeUntilTrue from './observeUntilTrue'; | |
//either use an a ko extension (just needs requir()ed once somewhere before now) | |
var isDirty = ko.observable(false).observeUntilTrue(() => { | |
// the real dirty check. make sure you access any/all observables you care to check in the future. | |
return isReallyDirty(); | |
}); | |
//or just as a plain function that we require in THIS module. | |
var isDirty = observeUntilTrue(() = { | |
// the real dirty check. make sure you access any/all observables you care to check in the future. | |
return isReallyDirty(); | |
}); | |
//or | |
var isDirty = observeUntilTrue(isReallyDirty); | |
// ==== TO RESET === | |
// just set it to false. that's it. It'll fire the dirty check (e.g. isReallyDirty()) right away to subscribe to all the observables. | |
isDirty(false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment