首页 > 解决方案 > nativescript - 在 exitEvent 上更改变量

问题描述

当应用程序关闭时,我需要能够更改某些变量的值。我正在使用此处描述的 exitEvent: https ://docs.nativescript.org/core-concepts/application-lifecycle

另外,我正在使用类似于 javasctip 的本地存储的本地存储插件。 https://github.com/NathanaelA/nativescript-localstorage

我的简单代码如下所示:

var Observable = require("data/observable").Observable;
require("nativescript-dom");
var LS = require("nativescript-localstorage");
const application = require("tns-core-modules/application");
var page = require("ui/page");

exports.load = function (args) {

var page = args.object;
var model = new Observable();
var frame = require('ui/frame');
var ff = frame.getFrameById("dashboard");
var topmost = frame.topmost();

// This is exit event
application.on(application.exitEvent, (args) => {
    LS.setItem('XX','111')
});


// What i will exit app, and run app again this will newer become 111,
it's null all the time
console.log(LS.getItem('XX'));
}

所以,我的问题是 - 可以在应用程序退出时设置任何标志 - 它不必是本地存储(我已经测试过全局变量),以检测是否退出,并基于此我可以做出决定会帮助我吗?

一种情况可能是 - 我在 Localstorage 中持有一些标志,即 TURE 是用户在登录屏幕上点击“rememebr me”。所以在退出时我可以检查他是否想要被记住,如果不是我想在应用程序启动时将用户发送到登录页面而不是仪表板......

谢谢你。

编辑:我也尝试过应用程序设置,它不起作用。

application.on(application.exitEvent, (args) => {
    applicationSettings.setString("Name", "John Doe");
});


console.log(applicationSettings.getString("Name")); // not working

标签: nativescript

解决方案


我怀疑是nativescript-localstorage插件的问题。它会在 250 毫秒延迟后将更改写入文件。在退出事件中,您将在您的应用程序完全被系统杀死之前给您非常有限的时间。

可能是作者有设置此延迟的原因,但我认为至少在这种特定情况下它的时间太多了,因此这些更改永远不会写入文件。您可以在插件的 Github 存储库中提出问题。

如果您正在寻找即时解决方法,请复制localstorage.js到您的应用程序并从文件中导出internalSaveData,这样您就可以在完成设置值后直接调用它。


推荐阅读