How to reference the same area of โ€‹โ€‹parent / grandparents with nested loops?

I have nested knockout loops. I would like to refer to something in the parent area. If you see below, I always want to refer to the same parent / grandfather and grandmother, no matter how deep I find the loops. I saw "with" binding, not sure if this will help me. Is there a way to create an alias for a specific area, so that further in the nested loop I can refer to this alias and still be able to refer also to the area of โ€‹โ€‹the current cycle?

    <!-- Somewhere up there is the "scope" I want to capture -->
    <!-- ko foreach: getPages() -->
        <span data-bind="text: pageName" ></span>
        <button data-bind="click: $parents[1].myFunction()" >Press me</button>
        <!-- ko foreach: categories -->
             <span data-bind="text: categoryName" ></span>
             <button data-bind="click: $parents[2].myFunction()" >Press me</button>
            <!-- ko foreach: questions -->
                <span data-bind="text: questionText" ></span>
                <button data-bind="click: $parents[3].myFunction()" >Press me</button>
             <!-- /ko -->
        <!-- /ko -->
    <!-- /ko -->
+5
source share
3 answers

foreach as, () withProperties .

<!-- ko withProperties: { book: $root.getBook() } -->
  <!-- ko foreach: {data: book.pages, as: 'page'} -->
    <span data-bind="text: page.pageName" ></span>
    <button data-bind="click: book.bookClicked" >Press me</button>
    <!-- ko foreach: {data: page.categories, as: 'category'} -->
      <span data-bind="text: category.categoryName" ></span>
      <button data-bind="click: page.pageClicked" >Press me</button>
      <!-- etc -->
    <!-- /ko -->
  <!-- /ko -->
<!-- /ko -->

$parent.

+2

@user2864740 , jsFiddle.

:

'withProperties'

, :

ko.virtualElements.allowedBindings.withProperties = true;

:

. : ReferenceError: 'book' is undefined; : foreach: {data: book.pages, as: 'page'}

, withProperties - book , .

(jsFiddle):

ko.bindingHandlers.withProperties = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // Make a modified binding context, with a extra properties, and apply it to descendant elements
        var value = ko.utils.unwrapObservable(valueAccessor()),
            innerBindingContext = bindingContext.extend(value);

        ko.applyBindingsToDescendants(innerBindingContext, element);

        // Also tell KO *not* to bind the descendants itself, otherwise they will be bound twice
        return { controlsDescendantBindings: true };
    }
};
ko.virtualElements.allowedBindings.withProperties = true;
+1

I think this will help you. Calling a function in the parent area in a nested view model.

and jsfiddle demo jsfiddle

0
source

All Articles