I have been using knockout and am familiar with the 'foreach' binding where i can use an alias 'as':
<ul data-bind="foreach: { data: categories, as: 'category' }">
<li>
<ul data-bind="foreach: { data: items, as: 'item' }">
<li>
<span data-bind="text: category.name"></span>:
<span data-bind="text: item"></span>
</li>
</ul>
</li>
</ul>
Is there a similar thing for the 'with' binding? I have tried it with the following code but get an error:
Uncaught ReferenceError: Unable to process binding "with: function (){return { data:$root.profileUser,as:'profile'} }"
<div data-bind="with: { data: $root.profileUser, as: 'profile' }">
<form class="form-horizontal">
<div class="form-group">
<label for="inputName" class="col-sm-2 control-label">Preferred Name</label>
<div class="col-sm-10">
<input type="text" data-bind="textInput: profile.PreferredName" class="form-control" id="inputName" placeholder="Preferred Name">
</div>
</div>
Knockout's declarative binding system provides a concise and powerful way to link data to the UI. It's generally easy and obvious to bind to simple data properties or to use a single binding. For more complex bindings, it helps to better understand the behavior and syntax of Knockout's binding system.
Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.
The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.
As you've demonstrated, the as
option with foreach
creates a persistent alias that you can reference in child contexts. If this is all you need, there's a new binding coming in the next version of Knockout (3.5.0), called let
.
You can you use it today by including the binding as a custom binding:
ko.bindingHandlers['let'] = {
init: function(element, valueAccessor, allBindings, vm, bindingContext) {
// Make a modified binding context, with extra properties, and apply it to descendant elements
var innerContext = bindingContext.extend(valueAccessor);
ko.applyBindingsToDescendants(innerContext, element);
return { controlsDescendantBindings: true };
}
};
ko.virtualElements.allowedBindings['let'] = true;
Usage:
<div data-bind="let: { profile: $root.profileUser }">
...
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With