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
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:
And in your component view-model:
See Fiddle