Created
May 28, 2014 05:42
-
-
Save jakiestfu/d2008742a4b1e61808cf to your computer and use it in GitHub Desktop.
This is an almost working "else" binding for Knockout.js. It monkey patches the "if" binding and keeps a stack of the last returned values from the bindings. Every "else" binding is actually an if binding with the negated value of the last if bindings return set in a preprocessor. Currently doesn't work with multiple bindings. DOH!
This file contains hidden or 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(){ | |
var bindingKey = 'else', | |
stack = [], | |
_if = ko.bindingHandlers.if, | |
_init = _if.init | |
_update = _if.update; | |
ko.bindingHandlers[bindingKey] = | |
{ | |
init: _init, | |
update: _update, | |
preprocess: function(val) | |
{ | |
if(!stack.length) throw new Error("Stray 'else' binding"); | |
// Negate this sonsa bitch | |
var last = stack.pop(); | |
var v = !last ? 'true' : 'false'; | |
return v; | |
} | |
}; | |
// Hijack the if binding | |
ko.bindingHandlers.if.init = function() | |
{ | |
var dataValue = ko.utils.unwrapObservable(arguments[1]()), | |
result = _init.apply(this, arguments); | |
stack.push(dataValue); | |
return result; | |
}; | |
// Virtualize this shit | |
ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; | |
ko.virtualElements.allowedBindings[bindingKey] = true; | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment