2

特定の時間にローカル通知を設定できる PhoneGap LocalNotification プラグインを使用しています。

LocalNotification プラグインの基本構造は次のようになります。

var notification = {
    init: function () {

    },
    clear_all: function () {
        notification.clear();
        plugins.localNotification.add({
            badge: 0,
        });

    },
    alert_ten: function () {
        var d = new Date();
        d = d.getTime() + 10 * 1000; //60 seconds from now
        d = new Date(d);
        plugins.localNotification.add({
            date: d,
            repeat: 'daily',
            message: varone + ' - ' + vartwo + '!',
            hasAction: true,
            badge: 1,
            id: '1',
            sound: 'horn.caf',
            background: 'app.background',
            foreground: 'app.running'
        });
    },
}

通知のメッセージ部分を見ると、以下のような構成になっていますvarone + ' - ' + vartwo + '!'。ページの読み込み時にvarone、アイテムvartwoから入力されlocalStorageます。notification.alert_ten()次に、 onLoadを呼び出します。

これはすべて正常に機能しますが、例外が 1 つあります。

localStorage項目は、ユーザーが特定の div を操作する (つまり、クリックする) ときに設定されます。次に、アプリが読み込まれると、これらの値がチェックされ、10 秒後に、LS から値を取得するthisとというメッセージが警告されます。that

ユーザーが気が変わって、LS 項目を変更する別の div と対話した場合でも、LocalNotification は LS 項目の元のセットで実行されます。

JS は関数内で変数をキャッシュするため、これは当然のことです。私がうまくいくと思った解決策は、上記の変数をグローバルに定義しvar notification = {、ユーザーが div を操作したときに、vars を更新して新しい変数を表すことです。

グローバル変数:

var varone = localStorage.getItem("favorite");
var vartwo = localStorage.getItem("favorite-status").substr(2).toLowerCase();
...

更新された変数:

...
var varone = text;
var vartwo = favstatus;
...

関数notification.alert_ten()は、更新された値ではなく、グローバル変数内で定義された元の値で引き続き実行されます。

4

1 に答える 1

1

ゲッター/セッター関数を書くことができます。これは概念実証にすぎません。これに任意のメソッドを追加できます。this.オブジェクト内の関数間で共有するプロパティ、またはオブジェクトの外部からアクセスできるプロパティの前に必ず追加してください。

var notification = {
  setX : function (newX) {
    this.x = newX;
  },
  getX : function () {
    return this.x;
  },
  outputX : function () {
    document.write('x is ' + this.x + '<br>');
  }
}

初期化して使用します:

notification.setX(42);
console.log(notification.getX());

また

notification[x] = 42;
console.log(notification[x]);

あるいは

notification.x = 42;
console.log(notification.x);

デモ

したがって、コードは次のようになります(興味深い部分を除くすべてを削除します)

var notification = {
    getMessage: function() {
        return this.message;
    },
    setMessage: function() {
        this.message = localStorage.getItem("favorite") + ' - ' + 
                       localStorage.getItem("favorite-status").substr(2).toLowerCase() + '!';
    },
    alert_ten: function () {
        plugins.localNotification.add({
            message: this.getMessage()
        });
    }
}

// After some event I guess
notification.setMessage();
// After some other event?
notification.alert_ten();
于 2012-10-24T02:39:29.693 に答える