Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout binding 'with' an alias 'as'

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>
like image 245
Lamb Chop Avatar asked Aug 31 '16 18:08

Lamb Chop


People also ask

What are Knockout bindings?

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.

What is Knockout used for?

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.

What is $data in Knockout?

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.


1 Answers

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>
like image 166
Michael Best Avatar answered Oct 07 '22 00:10

Michael Best