2013-04-13 19 views
2

我正在創建一個Windows 8 HTML5應用程序,並實現了一個應用程序欄。當我訪問appbar.winControl時,它始終爲空。因此,如果例如我寫appbar.winControl.show()我得到一個異常,聲明winControl爲空。winjs appbar.wincontrol爲空

我做的是創建一個固定的佈局應用程序。如果沒有其他人在做什麼,我說在文檔正文中的以下標記:

<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> 

線winControl.show()產生以下錯誤:

0x800a138f - JavaScript運行錯誤:無法獲取屬性「顯示」未定義或空引用

據我所見,我已經在頁面上正確實施了appbar,所以它應該工作。任何想法出了什麼問題?

回答

3

頁面控件尚未初始化,腳本在此之前正在執行。

這個代碼有兩個放置位置。無論是在

// 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(); 
}); 

// 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(); 
     } 
    } 
+0

謝謝@Sushil。我無法得到第一個例子 - 而是得到一個錯誤,指出processAll函數不存在。但第二個例子完美運行,所以我的問題解決了。 –

+0

我必須修改它。現在我可以讓兩個實例工作。我不知道爲什麼第一個例子早些時候沒有工作,但這可能是我無法識別的輸入錯誤。無論如何,再次感謝@Sushil –

1

每當你使用winjs控制(分度數據雙贏的控制屬性)來指定要控制。 您還必須在JavaScript代碼中調用WinJS.UI.processAll函數。 WinJS.UI.processAll會解析您的標記並實例化它找到的任何Windows庫for JavaScript控件。

  1. 如果您使用的不是空白應用程序模板,或者如果你
    添加控件到您創建自己頁面,則可能
    需要添加到WinJS.UI.processAll通話。
  2. 如果您添加了控制 到你的應用程序的主頁(這通常是default.html和文件), 添加到WinJS.UI.processAll來電您onactivated事件 處理程序,如前面的例子中
  3. 如果將控件添加到Page控件,則不需要添加對 WinJS.UI.processAll的調用,因爲Page控件會自動爲您執行 。
  4. 如果您將控件添加到另一個不是您的應用程序的主頁的頁面,請處理DOMContentLoaded事件並使用該處理程序調用WinJS.UI.processAll。

函數初始化(){

WinJS.UI.processAll(); 

}

document.addEventListener( 「DOMContentLoaded」,初始化(),假);