javascripthtmlknockout.jsknockout-componentsknockout-templating

How do I access my viewmodel variables in my knockout component template?


I am trying to create a list of instruction steps using Knockout components/templates.

The UL is the going to contain a list of steps (using a knockout-registered custom element sidebar-step) which is just a template of <li></li>. I have another value this.testVar part of my model that could contain an attribute of <li> such as the class, or maybe a "data-customAttribute".

My question is, how do I include my testVar value into the template? I want it so that it might output a line like:

<sidebar-step class=*testVar* params="vm: sidebarStepModel">Message 1</sidebar-step>

Fiddle: https://jsfiddle.net/uu4hzc41/1/

HTML:

<ul>
    <sidebar-step params="vm: sidebarStepModel"></sidebar-step>
</ul>

JavaScript:

ko.components.register("sidebar-step", {
    viewModel: function (params) {
        this.vm = params.vm;
    },

    template: "<li data-bind=\'text: vm.message\'></li>"
});

var SidebarStepModel = function () {
    this.message = ko.observable("step description");
    this.testVar = ko.observable("some value");
};

var ViewModel = function () {
    this.sidebarStepModel = new SidebarStepModel();
    this.sidebarStepModel.message("Message 1");
    this.sidebarStepModel.testVar("69");


};

ko.applyBindings(new ViewModel());

Solution

  • You can use data-bind on the custom tag. To set class,

    <sidebar-step data-bind="css:sidebarStepModel.testVar" params="vm: sidebarStepModel"></sidebar-step>
    

    https://jsfiddle.net/uu4hzc41/3/