Search code examples
knockout.jsparameter-passingknockout-components

knockout component parameter handling


I just don't seem to understand the following:

I have a html page that uses a knockout component see code below:

HTML:

<h2>Home</h2>
<p data-bind='text: message'></p>
<examlist params="list: StartList"></examlist>

So passing a parameter to the examlist

In my knockout examlist component viewmodel:

define(['knockout', 'text!./examlist.html'], function(ko, templateMarkup) {

function Examlist(params) {
    this.message = ko.observable('Hello from the examlist component!');
    this.typeOfList = params.list;
    console.log(this.typeOfList);

I'm getting an error in my console :

Uncaught ReferenceError: StartList is not defined

The examlist html tag markup:

<h2>examlist</h2>

<p data-bind='text: message'></p>

Why is this?

And in my viewmodel can I directly access the params.list for an if statement?

Thanks for your help in advance.

Regards,


Solution

  • You need viewModel with lists to bind, something like

    function MainViewModel() {
        this.list1 = [1, 2, 3];
        this.list2 = ["test", "it", "work"];
    }
    
    var viewModel = new MainViewModel();
    
    ko.applyBindings(viewModel);
    

    Than you can bind params like

    <examlist params="list: list1"></examlist>
    <examlist params="list: list2"></examlist>
    

    or just pass array of values explicitly:

    <examlist params="list: [5, 6, 7]"></examlist>
    

    Working sample