Stephen James
Stephen James

Reputation: 1287

How to not repeat explicit settings on Durandal widget bindings

I'm mocking up a website using Durandal to keep my knockout js neat but admittedly am a beginner when Durandal is concerned.

Frequently I need to iterate over an array of items in the viewModel and bind widgets, but I'm finding that I'm having to repeat the 'settings' bindings explicitly.

for example :

<section data-bind="foreach: secondaryKpis" class="row">
    <div data-bind="widget: {
        kind: 'kpiSecondary',
        name: $data.name,
        columns: $data.columns,
        delta: $data.delta,
        description: $data.description,
        vsDelta: $data.vsDelta,
        vsDescription: $data.vsDescription
    }">
    </div>
</section>

In the context of the foreach, $data already holds all the properties that I would like to bind to the custom widget kpiSecondary and typing { someProperty: $data.someProperty, ... } seems a bit redundant.

I know I could do something like :

<section data-bind="foreach: secondaryKpis" class="row">
    <div data-bind="widget: {
        kind: 'kpiSecondary',
        data: $data
    }">
    </div>
</section>

but that would require me to unwrap the data variable into this.settings in the custom widget, is this the right way to go about it or is there a clean and standard method to do this that I just haven't come across yet?

Upvotes: 0

Views: 93

Answers (1)

mms27
mms27

Reputation: 826

To make your code easier to support, add getOptionsFor method to your viewmodel:

getOptionsFor: function (item) {
  return {
    name: item.name,
    descr: item.descr
    //etc
  }
}

In this case, your html will look like that:

<div data-bind="foreach: { data: targetArray, as: 'item' }">
  <div data-bind="widget: $parent.getOptionsFor(item)"></div>
</div>

Upvotes: 2

Related Questions