如何在不使用WinjS库的情况下在通用Windows应用程序中添加后退按钮事件?

时间:2016-09-09 06:52:10

标签: javascript uwp windows-10-universal

这是我的main.js

(function () {
"use strict";

//No need of WinJS
var activation = Windows.ApplicationModel.Activation;
var roaming = Windows.Storage.ApplicationData.current.roamingSettings;

// For App Start Up
Windows.UI.WebUI.WebUIApplication.addEventListener("activated", function (args) {
    if (args.detail[0].kind === activation.ActivationKind.launch) {
        if (roaming.values["currentUri"]) {
            if (roaming.values["UserName"])
            {
                localStorage.setItem("UserName", roaming.values["UserName"]);
                window.location.href = roaming.values["currentUri"];
            }
        }
    }
});

// For App Suspension
Windows.UI.WebUI.WebUIApplication.addEventListener("suspending", function (args) {
    roaming.values["currentUri"] = window.location.href;
    roaming.values["UserName"] = localStorage.getItem("UserName");
});

// For Resuming App
Windows.UI.WebUI.WebUIApplication.addEventListener("resuming", function (args) {
    var roam = Windows.Storage.ApplicationData.current.roamingSettings;
    if (roam) {
        if (roam.values["currentUri"]) {
            localStorage.setItem("UserName", roam.values["UserName"]);
            window.location.href = roam.values["currentUri"];
        }
    }
}, false);
// not working backpressed event
Windows.UI.WebUI.WebUIApplication.addEventListener("backpressed", function (args) {
   // to do
}, false);})();

我需要在不使用winjs库的情况下为Windows Phone添加按键事件? 谁能建议我?

我在我的应用中使用ms-appx-web上下文。我不想使用winjs库。

2 个答案:

答案 0 :(得分:1)

  

我需要在不使用winjs库的情况下为Windows Phone添加按键事件?

backpressed事件应附加到Windows.Phone.UI.Input.HardwareButtons但不附加Windows.UI.WebUI.WebUIApplication

如果您引用HardwareButtons.BackPressedHardwareButtons,您会发现backpressed事件的使用方式如下:

var hardwareButtons = Windows.Phone.UI.Input.HardwareButtons;
function onBackPressed(eventArgs) { /* Your code */ }

// addEventListener syntax
hardwareButtons.addEventListener("backpressed", onBackPressed);
hardwareButtons.removeEventListener("backpressed", onBackPressed);

因为你没有制作单页应用程序。这个事件应该附在每个新页面的JS代码上。

更新:如果您想以编程方式了解当前设备,可以使用以下if语句:

if (deviceInfo.operatingSystem.toLowerCase() == "windowsphone")
{
     //do your windows phone logic
} else if (deviceInfo.operatingSystem.toLowerCase() == "windows")
{
     //do your windows logic
}

答案 1 :(得分:0)

我用过这个 -

var flag = Windows.Foundation.Metadata.ApiInformation.isTypePresent("Windows.Phone.UI.Input.HardwareButtons");

    if (flag) {
        var hardwareButtons = Windows.Phone.UI.Input.HardwareButtons;
        hardwareButtons.addEventListener("backpressed", onBackPressed);
    }

这对我有用!