Easiest way to fix ghost clicks in jQuery Mobile + PhoneGap?

有些话、适合烂在心里 提交于 2019-12-25 05:22:32

问题


I can't seem to find any straightforward way of fixing this? I can't wrap my head around Google's Fast Buttons approach. So if anyone has an alternative, that would be really nice.

The ghost clicks I'm talking about is referring to the touch on a button or something that triggers it multiple times. For example, clicking a button that will show alert("hello"); will show that said alert box 2 or sometimes even 5 times.

This is part of my code that handles button pressing. I omitted some parts but basically, that's the mechanism that handles presses on the "add" button.

$('div:jqmData(role="page")').live('pagebeforeshow',function(){
    var db = window.openDatabase("mydb", "1.0", "MyDB", 1000000);

    var url = window.location.href;
    var filename = url.substring(url.lastIndexOf('/')+1);

    switch (filename) {
        case "index.html":
            $("#add").tap(function(e){
                if ($("#info").val() == "") {
                    navigator.notification.alert("The info cannot be blank!", function(){}, "Error", "Okay, got it!");
                } else {
                    db.transaction(addToDb, errorCB, addedToDb);
                }
            });
            break;
        case "sample.html":
            break;
    }
});

回答1:


You've got a standard event binding happening inside of a delegated event binding. That means that the inner-binding will be bound every time the outer-event fires.

So basically you're re-binding your tap event handler each time the pagebeforeshow fires for any pseudo-page. Each time you navigate to another page you're creating another inner-binding so you're getting multiple alerts.

A good fix is to create a delegated event handler for the pageinit page-event and do the inner-binding in that event handler. The pageinit event only fires once per pseudo-page so you won't keep adding more event handlers unnecessarily.

For Example:

$(document).on('pageinit', '.ui-page',function(){
    var db       = window.openDatabase("mydb", "1.0", "MyDB", 1000000),
        url      = window.location.href,
        filename = url.substring(url.lastIndexOf('/')+1);

    switch (filename) {
        case "index.html":
            $("#add").tap(function(e){
                if ($("#info").val() == "") {
                    navigator.notification.alert("The info cannot be blank!", function(){}, "Error", "Okay, got it!");
                } else {
                    db.transaction(addToDb, errorCB, addedToDb);
                }
            });
            break;
        case "sample.html":
            break;
    }
});

You'll notice I used .on() for my delegated event handler instead of the depreciated .live().



来源:https://stackoverflow.com/questions/12794160/easiest-way-to-fix-ghost-clicks-in-jquery-mobile-phonegap

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