Skip to content Skip to sidebar Skip to footer

Restrict Jqm Panel To Only 1 Instance On Page

I'm developing a JQM theme using single pages. I also have a side bar / panel that is built as a seperate html file. This panel is imported into the JQM page using the following J

Solution 1:

The pagebeforecreate event will emit on each and every page, but only ONCE. If you have 5 pages in one HTML file (Multi-Page Model), that event will fire 5 times before creating/showing the target page.

This event can't be delegated to a specific page, e.g. the below code won't work.

$(document).on("pagebeforecreate", "#pageX", function (event) {
  /* do something to pageX */
});

unlike pagecreate which can be delegated to a specific page.

$(document).on("pagecreate", "#pageX", function (event) {
  /* use it to add listeners */
});

However, you can obtain an object of that page which is being created.

$(document).on("pagebeforecreate", function (event) {
  var page = event.target.id;
  if ( page == "pageX") {
    /* do something to pageX */
  }
});

Why .one()?

Since pagebeforecreate can't be delegated and it fires on each page, using .one() will run code once only. However, if you repeat the same code using .one() that code will be executed it again.

Altenative approaches:

  1. Check whether panel is added before adding it.

    $(document).one('pagebeforecreate', function () {
        var panelDOM = $("[data-role=panel]").length;
        if (panelDOM === 0) {
            /* add panel */
        } else {
            /* nothing */
        }
    });
    

    Demo

  2. Use mobileinit as it fires once per document/framework. This event fires before loading jQM, so you will need to enhance/_initialize_ panel after loading jQM.

    <scriptsrc="jquery-1.9.1.min.js"></script><script>/* inject panel */
        $(document).on("mobileinit", function() {
            var panel = '<div>panel</div>';
            $("body").prepend(panel);
        });
    </script><scriptsrc="jquery.mobile-1.4.2.min.js"></script><script>/* initialize it */
        $(function() {
            $("[data-role=panel]").panel().enhanceWithin();
        });
    </script>

    Demo

Post a Comment for "Restrict Jqm Panel To Only 1 Instance On Page"