Skip to content

Instantly share code, notes, and snippets.

@jakiestfu
Created May 28, 2014 05:42
Show Gist options
  • Save jakiestfu/d2008742a4b1e61808cf to your computer and use it in GitHub Desktop.
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!
(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