Skip to content

Instantly share code, notes, and snippets.

@dfrencham
Created July 17, 2015 03:52
Show Gist options
  • Save dfrencham/b759169461003e424906 to your computer and use it in GitHub Desktop.
Save dfrencham/b759169461003e424906 to your computer and use it in GitHub Desktop.
Knockout 3.3 Nested Components
<div style="border:1px solid blue; margin: 5px; padding: 5px;">
<label data-bind="text: labelText"></label>
<input type="text" />
</div>
define(['knockout'], function(ko) {
function NiftyListItemViewModel(params) {
this.labelText = params.labelText;
}
console.debug('component loaded');
return NiftyListItemViewModel;
});
<div style="border:1px solid red; margin: 5px; padding: 5px;">
<strong>
<div data-bind="text: componentText">
</div>
</strong>
<!-- ko template: { nodes: $componentTemplateNodes } --><!-- /ko -->
</div>
define(['knockout'], function(ko) {
function NiftyListViewModel(params) {
this.componentText = params.componentText;
}
console.debug('component loaded');
return NiftyListViewModel;
});
<html>
<body>
<h1>How to create knockout nested components</h1>
<p>Note that this code is reliant on require.js and knockout</p>
<p>Components should be placed in a folder structure as follows: /Components/name/(view/viewmodel)</p>
<nifty-list-item params='labelText:"component that isnt nested"'></nifty-list-item>
<nifty-list params='componentText:"text passed to component"'>
<nifty-list-item params='labelText:"nested component 1"'></nifty-list-item>
<nifty-list-item params='labelText:"nested component 2"'></nifty-list-item>
<nifty-list-item params='labelText:"nested component 3"'></nifty-list-item>
</nifty-list>
<script>
ko.components.register('nifty-list', {
viewModel: { require: 'components/nifty-list/viewmodel' },
template: { require: 'text!components/nifty-list/view.html' }
});
ko.components.register('nifty-list-item', {
viewModel: { require: 'components/nifty-list-item/viewmodel' },
template: { require: 'text!components/nifty-list-item/view.html' }
});
</script>
</body>
</html>
@dfrencham
Copy link
Author

This gist demonstrates the use of nested Knockout Web Components (well, Knockout's "web component inspired" components).

This code assumes your folder structure is:

  • /Components
    • /Component-name
      • view.html
      • viewmodel.js

Libraries required:

  • Knockout.js (3.3)
  • require.js
  • text.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment