1
votes

when I use knockout component, I got a bind error. HTML:

<html >
<head>
<link rel="stylesheet" href="css/default.css">
</head>

<body>

    <main id="shell">

        <!-- logo & top level links -->
        <header>
            <header-widget></header-widget>
        </header>

    </main>

    <script type="text/javascript" src="thirdparty/requirejs/require-2.3.3.js" data-main='./js/requirejs.config'></script>
</body>

java script:

var requireConfig = {
    baseUrl: './',
    paths: {
        jquery: 'thirdparty/jquery/jquery-1.11.2',
        ko: 'thirdparty/knockout/knockout-3.4.2',
        text: 'thirdparty/requirejs/text'
    },
    shim: {

    }
};
require.config(requireConfig);
define(
    function(require) {
        require(['jquery', 'ko'], function($, ko) {
            var modle = {
            };
            $(document).ready(function() {
                ko.components.register('header-widget', {
                    viewmodel: function(params){
                        this.username = ko.observable('tom');
                    },
                    template: '<div data-bind="text:username">userxxx</div>'
                });
                ko.applyBindings(modle);

            });
        });
    }
);

I check the name, they are correct. I couldn't figure out why the binding is failing. I check the stackoverflow.com but can't find a question same as this.can you help me?

2

2 Answers

1
votes

I found the reason. When I pass params to ko.components.register, the view-model param name is incorrect. The viewmodel: function(params){ should be viewModel: function(params){.

0
votes

When you're using a custom element ike this, you don't need to supply a model when you call applyBindings. I think all you need to do is:

  1. Get rid of this code:

    var modle = {
    };
    
  2. Reduce your applyBindings call to just:

    ko.applyBindings();
    

This is because the view-model for the component is already defined in your ko.components.register block.