Javascript 如何使用嵌套循环引用相同的父/祖父母作用域?

Javascript 如何使用嵌套循环引用相同的父/祖父母作用域?,javascript,knockout.js,Javascript,Knockout.js,我有带敲除的嵌套循环。我想提及父“范围”中的某些内容。如果你在下面看到,我总是想指的是同一个父母/祖父母,不管我嵌套的循环有多深。我看过“with”绑定,不确定它是否对我有帮助。是否有任何方法可以创建特定范围的别名,以便在嵌套循环中进一步引用此别名,并且仍然能够引用当前循环的范围 <!-- Somewhere up there is the "scope" I want to capture --> <!-- ko foreach: getPages() --&

我有带敲除的嵌套循环。我想提及父“范围”中的某些内容。如果你在下面看到,我总是想指的是同一个父母/祖父母,不管我嵌套的循环有多深。我看过“with”绑定,不确定它是否对我有帮助。是否有任何方法可以创建特定范围的别名,以便在嵌套循环中进一步引用此别名,并且仍然能够引用当前循环的范围

    <!-- 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 -->

按我
按我
按我
我想这会对你有所帮助

还有JSFIDLE演示

与支持别名一样,支持别名


按我
按我
我的声明性绑定没有一个直接使用
$parent

的问题是它不能开箱即用

第一个问题:

绑定“withProperties”不能与虚拟元素一起使用

要解决此问题,只需添加以下代码:

ko.virtualElements.allowedBindings.withProperties = true;
之后,您将获得另一个异常:

无法分析绑定。消息:ReferenceError:“book”为 未定义;绑定值:foreach:{data:book.pages,as:'page'}

这表明
withProperties
根本不起作用-它没有像您所期望的那样在绑定上下文中为其子绑定创建
book
属性

以下是完全工作且可重复使用的自定义绑定()

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;
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;