DEV Community 👩‍💻👨‍💻

Discussion on: Setting up ASP.NET Core in Visual Studio 2017 with npm, webpack, and TypeScript: Part II

dununubatman profile image
Joshua Dale

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?

Thread Thread
t4rzsan profile image
Jakob Christensen Author

An easy way to it is to place your views inside containers with IDs:

<div id="myview-container">
    <span data-bind="text: firstname"></span>
    <!-- ... -->
Enter fullscreen mode Exit fullscreen mode

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]);
Enter fullscreen mode Exit fullscreen mode

Don't forget to first install jQuery with npm:

npm install --save-dev jquery @types/jquery
Enter fullscreen mode Exit fullscreen mode

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.