I am working with the new components functionality of knockout 3.2 and trying to load the components using requireJS. However, I am having a weird issue. Basically, when I hardcode the view model in the register function everything works fine. When I try to load the exact same view model using requireJS, it's not working correctly.
Here's a sample of the html to load the component:
<div data-bind="component: { name: 'test'}"></div>
Here's the html in the template that this component will load:
<a href="#" data-bind="click: addNew">add</a>
<span data-bind="visible: Adding">test</span>
When I write my register function as shown below, everything works as expected (meaning that when this gets loaded, the "test" text does not show until the user clicks the "add" link):
ko.components.register('test',
{
template: { require: 'text!path/theTemplateFromAbove.html' },
viewModel:
function() {
var self = this;
self.Adding = ko.observable(false);
self.addNew = function() {
self.Adding(true);
}
}
});
But if I try to change this to use requireJS to load the view model, it doesn't work. The "test" text displays immediately without the user clicking the "add" link. The observables on the view model are getting messed up somehow.
Here's the script file contents (note the view model is the same):
define(["knockout"], function (ko) {
function viewModel() {
var self = this;
self.Adding = ko.observable(false);
self.addNew = function () {
self.Adding(true);
}
};
return viewModel;
});
And the register function would now look like this:
ko.components.register('test',
{
template: { require: 'text!path/theTemplateFromAbove.html' },
viewModel: { require: 'path/fileForMyTemplate' }
});
While debugging the issue, I added a check in the resolveViewModel function of knockout-3.2.0. After it calls new viewModelConfig(params), I check if "Adding" is an observable on the object. When the view model is hardcoded in the register function, it returns true. When I use requireJS to load the view model, it returns false.
Any ideas on what I'm doing wrong here?
[copied from comment as a answer to avoid confusion]
Is your
ko.components.register
line wrapped inside a requirejs module?I suspect you load javascript file
knockout.js
beforerequire.js
file, and then you access globalko
variable to doko.components.register
which is a differentko
object from the one loaded byrequire.js
.