Search code examples
knockout.jsdurandal

Durandal composition foreach


I'm looping through an array and displaying its content through a composition

<!-- ko foreach: { data: datas} -->
    <div>
            <!-- ko compose: {
                model: 'show',
                activationData: {
                    bundle:bundle
                },                    
               } -->
            <!-- /ko -->
    </div>  
<!-- /ko -->

the composition calls a model show.js, that takes the activationData bundle wraps it in an observable and display it in a table

function (logger, utils) {
    var bundle = ko.observable();

    var activate = function (data) {
        // process data.bundle further 
        bundle(populateBundle(data.bundle));
    };
}

show.html

<table class="table table-bordered">
    <tbody>        
        <!-- ko foreach: {data:bundle().groups, as:'group'} -->
        <tr>
            <td class="tolerances-values" align="center"><span data-bind="text: group.name"></span></td>
            <td class="tolerances-values" align="center"><span data-bind="text: group.code"></span></td>

        </tr>
        <!-- /ko -->
    </tbody>
</table>

All works well, however when i'm looping though more than one data all the compositions displayed previously display the content of the last element. I know it's linked to the fact that i'm using bundle as an observable, how can i for the composition to treat every bundle sent to the composition as an isolated observable though ? Am I missing anything


Solution

  • The reason is because you aren't using a constructor function inside of your view model. You need to create an object and attach things like activate onto it's prototype instead of the way that you are doing it. Check here for an example - http://durandaljs.com/documentation/Using-Composition.html

    Here is another example from the message box docs -

    var MessageBox = function(message, title, options) {
        this.message = message;
        this.title = title || MessageBox.defaultTitle;
        this.options = options || MessageBox.defaultOptions;
    };
    
    MessageBox.prototype.selectOption = function (dialogResult) {
        dialog.close(this, dialogResult);
    };