Search code examples
javascriptwinjswindows-phone-8.1

How to bind PivotItems dynamically to html pages


So I'm trying to create an app with a WinJS.UI.Pivot control. The documentation is very simple, and the samples I've seen are "for dummies".

I know I can add my html under the PivotItem control and I've also seen a way of binding the control of a child element vie the data-win-control to a ControlConstructor that defines a page in a javascript file, as seen here:

    (function () {
        "use strict";

        var ControlConstructor = WinJS.UI.Pages.define("/pages/hub/section1Page.html", {
            // This function is called after the page control contents 
            // have been loaded, controls have been activated, and 
            // the resulting elements have been parented to the DOM. 
            ready: function (element, options) {
                options = options || {};
            },
        });

        // The following lines expose this control constructor as a global. 
        // This lets you use the control as a declarative control inside the 
        // data-win-control attribute. 

        WinJS.Namespace.define("HubApps_SectionControls", {
            Section1Control: ControlConstructor
        });
    })();

Is there a way to do this dynamically (programmatically)?


Solution

  • Here's a sneak peak of some code from the upcoming new release of codeShow which will work on the phone.

    //render pivot items for sections
    var sectionsPivot = element.querySelector(".sections").winControl;
    options.demo.data.sections.forEach(function (section) {
        var pivotItem = new WinJS.UI.PivotItem(document.createElement("div"), { isHeaderStatic: true, header: section.title });
        pivotItem.element.classList.add(options.demo.data.name);
        var pivotItemContent = pivotItem.element.querySelector(".win-pivot-item-content");
        WinJS.UI.Pages.render(Ocho.Utilities.format("/demos/{0}/{1}/{1}.html", options.demo.data.name, section.name), pivotItemContent)
            .then(function (page) {
                //remove the section header since the demo page has one already
                var header = page.element.querySelector("header.page-header");
                if (header) header.style.display = "none";
            });
        sectionsPivot.items.push(pivotItem);
    });
    

    The WinJS.UI.PivotItem is being created in a new (in-memory) div element, some content is being added to the pivot item's content child, and then I'm pushing it into the pivot control's items collection. Hope that helps.