JSFiddle - React, Tailwind, and code Playground
by kougiland
HTML
Example: Adding extra levels in the binding context hierarchy
<div>
<h1 data-bind="text: title"></h1>
<!-- notice that there is no separate 'with:' binding needed -->
<form data-bind="withSmartForm: formModel">
<input type="text" data-bind="value: name"/>
<input type="text" data-bind="value: email"/>
</form>
</div>
JavaScript
ko.bindingHandlers.withSmartForm =
{
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext)
{
element.style.backgroundColor = '#f00';
// Make a modified binding context, with a extra properties, and apply it to descendant elements
var newProperties = valueAccessor(),
childBindingContext = bindingContext.createChildContext(viewModel);
ko.utils.extend(childBindingContext, newProperties);
ko.applyBindingsToDescendants(childBindingContext, element);
// Also tell KO *not* to bind the descendants itself, otherwise they will be bound twice
return { controlsDescendantBindings: true }
},
update: function(element, valueAccessor)
{
}
};
function FormModel()
{
this.name = ko.observable("kougi");
this.email = ko.observable("[email protected]");
}
function MainModel()
{
this.title = "Title1";
this.formModel = new FormModel();
}
ko.applyBindings( new MainModel() );