Quantcast
Channel: Oracle Bloggers
Viewing all articles
Browse latest Browse all 19780

How to Separate HTML Templates in Knockout Apps

$
0
0

A problem with the solution discussed in the recent YouTube clip about component-based Knockout.js development is that you end up with your HTML template embedded in your JavaScript file, as shown below:

From a tooling perspective, the above is suboptimal because you're not able to benefit from code completion and syntax coloring that an HTML editor provides. One approach would be to create an extension to NetBeans that would somehow recognize the above construct as being HTML (i.e., if a "template" binding is encountered, treat everything that follows as HTML), which is doable and something I'll take a look into (using this as a starting point). And here's the initial result of looking into this, i.e., compare the string in the pic above to the string in the pic below; in the lower pic notice the HTML syntax coloring:


However, in a real Knockout application, you're more likely to separate out your HTML into separate files, thus making it possible to hand those HTML files over to your front-end designers, while you continue working separately on the business logic in your JavaScript files.

Starting with this useful article on the Knockout site, I restructured the application discussed in the YouTube clip so that its HTML is now separated out from the JavaScript, which has as an added benefit that all the Knockout support features available out of the box in NetBeans are available to you:

To get to the above point, I followed various articles where 'requirejs' and 'requirejs-text' are described. My application now looks like this:

And here's my 'appViewModel.js', which still has some work to be done to it, i.e., I need to use 'require.config', which is the next topic I'll be looking at. However, in the meantime, here's how things are set up to get to the above point:

define(['../bower_components/knockout/dist/knockout','../bower_components/requirejs-text/text'
],
function (ko) {
    return function appViewModel() {
        ko.components.register("user", {
            viewModel: function (params) {
                this.firstName = ko.observable(params.firstName);
                this.lastName = ko.observable(params.lastName);
                this.fullName = ko.pureComputed(function () {
                    return this.firstName() + "" + this.lastName();
                }, this);
            },
            template: {require: '../../requirejs-text/text!../../../../../files/user-template.html'}
        });
    };
}); 

The rest is the same as here. Finally, as in the YouTube clip, you use the above defined 'user' component in your 'index.html' as follows, again supported by code completion and other Knockout-friendly features in NetBeans:



Viewing all articles
Browse latest Browse all 19780

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>