IT:AD:Durandal.JS:HowTo:Include Components
- See also:
Summary
A component is a reusable View/ViewModel combo.
Durandal's documentation calls it Object Composition (as oppossed to Visual Composition which I find easier to understand as Partials).
Process
Composer
Components are included using compose
, pointing to the ViewModel (not the View's html file).
<div data-bind="compose:'viewmodels/components/header'"/>
or the fuller syntax:
<div data-bind="compose: {model:'viewmodels/components/header'}"/>
or either one, in the containerless syntax:
<!-- ko compose:{view:'viewmodels/components/header'} --><!--/ko-->
Notice how when using the full syntax, you need to include the leading viewmodels/
–
which differs from the behaviour of including Partials,
which in both cases, doesn't want the leading 'views/')
Alternatively, if you don't want a container, there is the alternative syntax:
<!--ko compose: { model:'viewmodels/components/headerCorpInfo'}-->
Debugging tips: * If it fails to load, and it says it can't resolve, or times out – it may be because the requires of the model are not resolving…
View
<section> <h4 data-bind="html: productDisplayName"/> <blockquote data-bind="html: productDisplayTagLine"/> </section>
Note that Components are binding to their own ViewModel's properties – not their Composer's ViewModel.
ViewModel
define( ['data/settings'], function (settings) { var model = function () { //Is this going to be this.view = { name : 'Application Information', description : null, } this.productDisplayName = settings.productInfo.displayName; this.productDisplayTagLine = settings.productInfo.displayTagLine; }; // model.prototype.viewAttached = function (view) { // //you can get the view after it's bound and connected to it's parent dom node if you want // }; //return singleton: return new model(); } );
Accessing Parent ViewModels
By default, each view gets its own binding context, separate and disconnected from its parent.
If a component needs to access to the ViewModel of its Composer,
File Location
It's just a suggestion, but I'll recommend that you keep components compartmentalized per zone:
/App/ /viewmodels /components (common) /zone1 /components (zone specific) /... /zoneN /components /views /components (common) /partials (common) /zone1 /components (zone specific) /partials (zone specific) /... /zoneN /components (zone specific) /partials (zone specific)