Quick note on WinJS templates and controls

Today I was working streaming (https://livecoding.tv/sorskoot) building my new JavaScript Audio Workstation. I wanted to use a template in a custom WinJS control but found it wasn’t in the samples.  Also, the MSDN documentation contained an error which made it even harder to get it to work.

Here’s an example:
(function () {
  WinJS.Namespace.define('jsaw.ui', { 
    menuBar: WinJS.Class.define(
      function (element, options) {
        this.element = element || document.createElement('div');
        this.element.winControl = this;
        this.options = options;
        this.createControl();
    }, {
      createControl: function () {
        WinJS.UI.Fragments.render('./app/templates/menubar.html',
                                  this.element)
                          .done(
                                /* Your success and error handlers */
                          );
      }
    })
  });
  WinJS.Class.mix(jsaw.ui.menuBar, WinJS.Utilities.eventMixin);
})();
In this example I create a WinJS class in the jsaw.ui namespace. This class has a constructor function (line 4) that calls the createControl function. In that function (line 10), a fragment is rendered. This fragment serves as a template for the control. All HTML in that control will be rendered and it will be cached as well. Note, that the Fragments object is in the UI namespace.