Local notification “schedule” and “trigger” methods are executing multiple times

China☆狼群 提交于 2019-12-11 10:26:52

问题


Hi I'm new on ionic and I'm using (katzer/cordova-plugin-local-notifications), I have a problem and I don't know what is happening.

When I click in a link, I'm generating a new notification. But I don't know for what when I click for the second time in the notification, the alert inside of "schedule" and "trigger" is executed two times, and when I click for the third time in the notification, the alert inside of "schedule" and "trigger" is executed three times, and so..

This is my code, it's very simple:

$scope.addNotification = function (){


    var idaudio = Math.round(Math.random() * 10000);
    var date = Date.now();

    cordova.plugins.notification.local.schedule({
        id: idaudio,
        title: 'Remember',
        text: 'New Remember',
        at: date

    });


    cordova.plugins.notification.local.on("schedule", function(notification){
        alert("scheduled: " + notification.id);
    });


    cordova.plugins.notification.local.on('trigger', function (notification){
        alert("trigger" + notification.id)
    });
}

I need that when I click in a notification only one alert print the related notification id.

Can anyone help me please?

Thanks in advance.


回答1:


Welcome to stackoverflow =)

With your code, every time you click to add a notification, you are adding event handlers for "schedule" and "trigger" events.

For example, the first time you click on addNotification, cordova.plugins.notification.local.on("schedule") will register and event handler to "functionA". The second time you click it, another event will be registered to "functionB", and so on. functionA, functionB,...will all be called when the "schedule" event is fired.

Solution, move your event handling code outside of the function.

$scope.addNotification = function (){
    var idaudio = Math.round(Math.random() * 10000);
    var date = Date.now();

    cordova.plugins.notification.local.schedule({
        id: idaudio,
        title: 'Remember',
        text: 'New Remember',
        at: date

    });

}

//this should only be registered once    
$scope.$on('$cordovaLocalNotification:schedule',function(notification) {
    alert("scheduled: " + notification.id);
});

//this should only be registered once    
$scope.$on('$cordovaLocalNotification:trigger',function(notification) {
    alert("triggered: " + notification.id);
});

//////notification.id must be set globally, otherwise it is gonna show as undefined.



来源:https://stackoverflow.com/questions/33511823/local-notification-schedule-and-trigger-methods-are-executing-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!