2016-07-11 26 views
0

根据以下示例,我将父集合(source: $parent.myThing.children)传递到自定义绑定中。我想知道在上下文中是否有任何内容告诉我父级集合在不知道名称的情况下?在不知道名称的情况下获取对foreach绑定中的集合的引用

<div data-bind="foreach: myThing.children"> 
    <button data-bind="arrayMoveUp: { item: $data, source: $parent.myThing.children }"> 
     <i class="fa fa-arrow-up"></i> Up 
    </button> 
    <button data-bind="arrayMoveDown: { item: $data, source: $parent.myThing.children }"> 
     <i class="fa fa-arrow-down"></i> Down 
    </button> 
</div> 

例如我希望能够做到像source: $source然后会通过什么的foreach必然。

回答

2

我不认为它是默认可访问的。您可以创建自定义扩展foreach结合,它增加了bindingContext虽然...

ko.bindingHandlers.customForEach = { 
 
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) { 
 
    ko.utils.extend(bindingContext, { 
 
     '$arraySource': ko.unwrap(valueAccessor()) 
 
    }); 
 

 
    return ko.bindingHandlers.foreach.init.apply(null, arguments); 
 
    }, 
 
    update: function() { 
 
    return ko.bindingHandlers.foreach.update.apply(null, arguments); 
 
    } 
 
}; 
 

 

 
ko.applyBindings({ 
 
    items: [1, 2, 3, 4, 5, 6] 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> 
 

 
<ul data-bind="customForEach: items"> 
 
    <li> 
 
    <span data-bind="text: $arraySource[$index() - 1]"></span> - 
 
    <strong data-bind="text: $data"></strong> - 
 
    <span data-bind="text: $arraySource[$index() + 1]"></span> - 
 
    </li> 
 
</ul>

相关问题