Eor*_*ori 2 knockout.js ko-custom-binding
有没有办法从自定义绑定内部绑定元素?例如,我有自定义绑定并绑定到它可观察的项目数组:
var someArrayOfItems = ko.observableArray(['item1', 'item2', 'item3']);
...
<div data-bind="myBinding: someArrayOfItems"></div>
Run Code Online (Sandbox Code Playgroud)
现在我希望myBinding列出它被绑定的div元素中的'someArrayOfItems'中的所有元素:
<ul data-bind="foreach: someArrayOfItems">
<li>
<span data-bind="text: $data"></span>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
是否可以使用自定义绑定进行此类操作?谢谢你的帮助.
RP *_*yer 10
您可以使用该函数ko.applyBindingsToNode
动态添加绑定到元素.
在您的情况下,您还需要使用适当的"模板"填充内容.
例如,您可以执行以下操作:
ko.bindingHandlers.myBinding = {
init: function(element, valueAccessor) {
var ul = document.createElement("ul"),
data = valueAccessor();
//append a new ul to our element
element.appendChild(ul);
//could use jQuery or DOM APIs to build the "template"
ul.innerHTML = "<li><span data-bind='text: $data'></span></li>";
//apply foreach binding to the newly created ul with the data that we passed to the binding
ko.applyBindingsToNode(ul, { foreach: data });;
//tell Knockout that we have already handled binding the children of this element
return { controlsDescendantBindings: true };
}
};
Run Code Online (Sandbox Code Playgroud)
此处示例:http://jsfiddle.net/rniemeyer/z458E/
归档时间: |
|
查看次数: |
4382 次 |
最近记录: |