【问题标题】:Local notification "schedule" and "trigger" methods are executing multiple times本地通知“计划”和“触发”方法执行多次
【发布时间】:2016-02-04 08:31:45
【问题描述】:

您好,我是 ionic 新手,我正在使用 (katzer/cordova-plugin-local-notifications),我遇到了问题,不知道发生了什么。

当我点击一个链接时,我正在生成一个新通知。但是我不知道为什么我在通知中第二次点击时,“schedule”和“trigger”里面的alert被执行了两次,当我在通知中第三次点击时,里面的alert "schedule" 和 "trigger" 执行了 3 次,以此类推..

这是我的代码,很简单:

$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)
    });
}

我需要当我点击通知时,只有一个警报会打印相关的通知 ID。

谁能帮帮我?

提前致谢。

【问题讨论】:

    标签: cordova notifications phonegap-plugins cordova-plugins localnotification


    【解决方案1】:

    欢迎来到stackoverflow =)

    使用您的代码,每次单击添加通知时,您为“计划”和“触发器”添加事件处理程序事件。

    例如,当您第一次点击 addNotification,cordova.plugins.notification.local.on("schedule") 将注册 和“functionA”的事件处理程序。 第二次点击它,另一个事件将被注册到“functionB”,以此类推。触发“schedule”事件时,functionA、functionB、...将全部调用

    解决方案,将您的事件处理代码移到函数之外。

    $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 必须全局设置,否则会显示为未定义。

    【讨论】:

    • 真的是一个很好的答案。它帮助我解决了问题并节省了很多时间。似乎需要对 onSchedule 和 onTrigger 函数进行一些修改。已经根据我的工作建议了。非常感谢您的宝贵回答。 :)
    • 您能否为 Ionic 2 提供相同问题的解决方案?我面临与上述问题相同的问题,
    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    相关资源
    最近更新 更多