Durandal composition foreach

一个人想着一个人 提交于 2019-12-13 04:27:24

问题


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


回答1:


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);
};


来源:https://stackoverflow.com/questions/21558768/durandal-composition-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!