javascripthtmlknockout.jsknockout-componentsknockout-templating

How can I make my Knockout.js components append to the page without erasing/overwriting any old bindings?


Fiddle: http://jsfiddle.net/mpqtsjhL/27/

Basically I have a Knockout.js component that uses a template:

JavaScript:

ko.components.register('sublist', {
    synchronous: true,
    viewModel: function (params) {},
    template: {
        element: 'my-component-template'
    }
});

HTML

<ul data-bind="component:{name:'sublist',params:{vm:sidebarVm}}" class=""></ul>
<template id="my-component-template">
    <!-- ko foreach: sidebarVm.stepList.steps-->
      <li data-bind="html: message"></li>
    <!-- /ko -->
</template>

I have multiple ViewModels that the user can load into that template with certain button clicks. As I have it now, when the user loads a new ViewModel, it overwrites the old one.

Desired Functionality: When the user clicks a button to load a new Viewmodel, those new list elements <li> get appended rather than replacing the existing ones. How?? In the Fiddle, there should be a total of 6 list elements in one list.

EDIT: Maybe I have to go somewhere along the lines in this new fiddle? Maybe something like this would allow me to instantiate multiple ViewModels within the <ul>. http://jsfiddle.net/mpqtsjhL/32/


Solution

  • Tbh, your usage of knockout is not as it is meant to be. If it are really ViewModels then make a "host" MainViewModel that manages the other ViewModels

      var MainMenuViewModel = function () {
        this.viewModels = ko.observableArray();
        this.viewModels.push(new ViewModel1());
    
        this.load=function(){
            this.viewModels.push(new ViewModel1());
        };
    }
    

    see updated fiddle http://jsfiddle.net/r2hsvsdg/1/

    btw, you can also handle the click logic using knockout

    better fiddle: http://jsfiddle.net/r2hsvsdg/4/