Search code examples
javascripthtmlwindows-8windows-runtimeappbar

winjs appbar.wincontrol is null


I am creating a Windows 8 HTML5 app, and implementing an app bar. When I access the appbar.winControl it is always null. So if for example I write appbar.winControl.show() I get an exception claiming that winControl is null.

What I did was create a fixed layout app. Without doing anything else, I added the following markup in the document body:

<body>
<div id="appbar" data-win-control="WinJS.UI.AppBar" aria-label="Command Bar">
    <button id="btnBoardSizeUp" data-win-control="WinJS.UI.AppBarCommand" data-win-options="{label:'Larger', icon:'zoomout', section:'global', tooltip:'Increase the board size'}" />
    <button id="btnBoardSizeDown" data-win-control="WinJS.UI.AppBarCommand" data-win-options="{label:'Smaller', icon:'zoomin', section:'global', tooltip:'Decrease the board size'}" />
    <button id="btnAbortGame" data-win-control="WinJS.UI.AppBarCommand" data-win-options="{label:'Abort', icon:'cancel', section:'selection', tooltip:'Abort the current game'}" />
</div>

<script type="text/javascript">
    var appbar = document.getElementById("appbar");
    var winControl = appbar.winControl;
    winControl.show();
</script>

The line winControl.show() produces the following error:

0x800a138f - JavaScript runtime error: Unable to get property 'show' of undefined or null reference

As far as I can see I have implemented the appbar correctly on the page, so it should work. Any idea what is going wrong?


Solution

  • Page Controls are not initialized yet and script is executing before that.

    There is two place this code can be placed. either in

    // if the app bar is part of default.html, appbar show can be put in default.js
    // default.js already have a call to WinJS.UI.processAll under activated event handler
    WinJS.UI.processAll().then(function ()
    {
        appbar.winControl.show();
    });
    

    or

    // if the appbar is part of mypage.html, need to have code like this in mypage.js
    WinJS.UI.Pages.define('/pages/mypage/mypage.html',
        {
             ready: function onready(element, options)
             {
                 appbar.winControl.show();
             }
        }