如何在JQM应用程序的所有页面中注册滑动事件?

时间:2013-06-12 11:41:05

标签: jquery jquery-mobile

我的应用程序有两个面板作为主布局,因此所有子页面都将包含这两个面板。现在,我想为应用程序中的所有页面注册滑动事件,以便用户可以从任何地方访问这两个面板。 我在这里创建了这个函数,这样我就可以调用它来从不同的地方注册:

function registerSwipeEvents() {
    //panel swipe from left and right for categories, favs.
    $(document).on("swipeleft swiperight", '[data-role=page]', function (e) {
        // We check if there is no open panel on the page because otherwise
        // a swipe to close the left panel would also open the right panel.
        // We do this by checking the data that the framework stores on the page element (panel: open).
        if ($.mobile.activePage.jqmData("panel") !== "open") {
            if (e.type === "swipeleft") {
                $(".right-panel").panel("open");
            } else if (e.type === "swiperight") {
                $(".left-panel").panel("open");
            }
        }
    });
}

我试过从pageinit调用此函数(仅运行一次脚本),pagebeforeshow和pageshow(总是运行),如下所示:

$('#HomePage').on('pageshow', function () {
    getFavouritesFromClient();

});

但是当我第二次从一个页面转到另一个页面时,该事件对所有页面都不起作用!也许我没有正确使用这些事件,但是到目前为止第一轮导航工作的最好的是页面显示。

1 个答案:

答案 0 :(得分:0)

此代码有助于在所有页面中注册滑动事件。

pagecreate事件将应用于所有页面(使用[data-role=page])。在此活动中,我们会找到该特定网页的ID $(this).attr('id')。然后,我们使用swipeleft

单独注册该特定页面的swiperight"#"+thisPageId个事件

(我在代码中包含了几行,这有助于我找出 - 对于那些有兴趣了解它的人来说)

//var glbl; // this helped me find the attribute - global variable for accessing via the console
$( document ).on( "pagecreate", "[data-role=page]", function() {
    //console.log($(this)); // uncomment this line to see this DIV
    //glbl = $(debug); //uncomment this line to assign this DIV to global variable "glbl", which you can then access via the console
    var thisPageId = $(this).attr('id');
    $( document ).on( "swipeleft swiperight", "#"+thisPageId, function( e ) {
        // We check if there is no open panel on the page because otherwise
        // a swipe to close the left panel would also open the right panel (and v.v.).
        // We do this by checking the data that the framework stores on the page element (panel: open).
        if ( $( ".ui-page-active" ).jqmData( "panel" ) !== "open" ) {
            if ( e.type === "swipeleft" ) {
                $( "#panelRight" ).panel( "open" );
            } else if ( e.type === "swiperight" ) {
                $( "#panelLeft" ).panel( "open" );
            }
        }
        console.log('on swipes');
    });
    console.log('on pagecreate');
});