In the view model .ts file you would then bind conditionally:
import * as ko from "knockout"
import * as $ from "jquery"
class MyViewModel {
firstname: KnockoutObservable<string>;
lastname: KnockoutObservable<string>;
constructor(firstname: string, lastname: string) {
this.firstname = ko.observable(firstname);
this.lastname = ko.observable(lastname);
}
}
var container = $("#myview-container");
if (container.length == 1) {
ko.applyBindings(new MyViewModel("Jakob", "Christensen"), container[0]);
}
Don't forget to first install jQuery with npm:
npm install --save-dev jquery @types/jquery
I updated the Github repository accordingly.
I personally think that this method is a bit clumsy. Another way (which I have not tried yet) is to use webpack code splitting. With code splitting you can tell webpack to create several bundles. That way you can create a webpack bundle for each of your views and view models.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Hi Joshua,
Normally you would apply the bindings in the .ts view model files. I updated the code accordingly in the blog post and on Github.
Thanks.
If you bundle the view models though wouldn't all the view model bindings get applied to the same view?
So you have the Home view and myviewmodel, if I add About and about_view_model, both bindings would be applied to both views because they are bundled?
An easy way to it is to place your views inside containers with IDs:
In the view model .ts file you would then bind conditionally:
Don't forget to first install jQuery with npm:
I updated the Github repository accordingly.
I personally think that this method is a bit clumsy. Another way (which I have not tried yet) is to use webpack code splitting. With code splitting you can tell webpack to create several bundles. That way you can create a webpack bundle for each of your views and view models.