I would like to be able to have a Knockout custom component that can have either static content or dynamic content using the foreach binding.
Last active
August 29, 2015 14:19
-
-
Save kaleb/f90a79e3275fe5dc21c8 to your computer and use it in GitHub Desktop.
KO Component With foreach Binding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<h2>Static - Items 1 through 3</h2> | |
<custom-element> | |
<span>item 1.1</span> | |
<span>item 1.2</span> | |
<span>item 1.3</span> | |
</custom-element> | |
<hr /> | |
<h2>Dynamic Attempt 1 - Items 1 through 3</h1> | |
<custom-element> | |
<!-- ko foreach: { data: ['item 2.1', 'item 2.2', 'item 2.3'], as: 'item' } --> | |
<span data-bind="text: item"></span> | |
<!-- /ko --> | |
</custom-element> | |
<hr /> | |
<h2>Dynamic Attempt 2 - Items 1 through 3</h1> | |
<custom-element data-bind="foreach: { data: ['item 2.1', 'item 2.2', 'item 2.3'], as: 'item' }"> | |
<span data-bind="text: item"></span> | |
</custom-element> | |
<script src="//rawgit.com/knockout/knockout/v3.3.0/dist/knockout.debug.js"></script> | |
<script id="tmpl" type="text/html"> | |
<!-- ko foreach: { data: $componentTemplateNodes, as: 'node' } --> | |
<!-- ko if: node.nodeType == 1 --> | |
<h3 data-bind="template: { nodes: [node] }"></h3> | |
<!-- /ko --> | |
<!-- /ko --> | |
</script> | |
<script> | |
ko.components.register('custom-element', { | |
template: { | |
element: 'tmpl' | |
} | |
}); | |
ko.applyBindings(); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment