KnockoutJS: Access to observable Variable outside of an custom component

1.7k views Asked by At

I already searched a lot but cannot figure out how to handle my issue. I created a custom component and the template is within a <script type="text/html"></script> Tag. Outside of this template I have a variable which I try to manipulate after doing something. This doesn't work, it's not defined. Is there any possibility to manipulate that observable?

My code looks like this:

HTML:

<customcomponent></customcomponent>
<script type="text/html" id="customcomponent-tpl">
    <span data-bind="text: foo">Foo</span>
    <span data-bind="text: bar">Bar</span>
</script>
<span data-bind="text: foobar">Foobar</span>

JS:

var customComponentViewModel = function() {
    this.foo = ko.observable();
    this.bar = ko.observable();
    this.foobar = ko.observable();

    this.foo('Foo!');
    this.bar('Bar!');
    this.foobar('Foo! Bar!');


    console.log(this.foo());
    console.log(this.bar());
    console.log(this.foobar());
};

// do another stuff...

/**
 * Register KO component
 */

ko.components.register('customcomponent', {
    viewModel: customComponentViewModel,
    template: {
        element: 'customcomponent-tpl'
    }
});

ko.applyBindings();

Many thanks in advance!

Matthias

1

There are 1 answers

0
haim770 On BEST ANSWER

The problem is that you don't have a view-model that is applied to the document at all, you only have a component view-model.

Try this:

var vm = { foobar: ko.observable('') };
ko.applyBindings(vm);

And in your component view-model:

ko.dataFor(document.body).foobar('Foo! Bar!');

See Fiddle