Skip to content

Instantly share code, notes, and snippets.

@jakiestfu
Created October 17, 2014 14:50
Show Gist options
  • Select an option

  • Save jakiestfu/51967fbd17d8278573c8 to your computer and use it in GitHub Desktop.

Select an option

Save jakiestfu/51967fbd17d8278573c8 to your computer and use it in GitHub Desktop.
An attempt to create an "else" binding with Knockout. Only supports linear statements, no depth.
(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)
{
console.log('_ELSE_');
if(!stack.length) throw new Error("Stray 'else' binding");
// Negate this sonsa bitch
var last = stack.pop();
var v = !last ? 'true' : 'false';
console.log('else',v, 'Last if value: '+ last);
return v;
}
};
// Hijack the if binding
ko.bindingHandlers.if.init = function()
{
var dataValue = ko.utils.unwrapObservable(arguments[1]()),
result = _init.apply(this, arguments);
console.log('if', dataValue);
stack.push(dataValue);
return result;
};
// Virtualize this shit
ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false;
ko.virtualElements.allowedBindings[bindingKey] = true;
})();
ko.applyBindings({});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment