DEV Community

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

 
t4rzsan profile image
Jakob Christensen

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

<div id="myview-container">
    <span data-bind="text: firstname"></span>
    <!-- ... -->
</div>
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.