storing a variable in localStorage is too slow

前端 未结 2 1820
醉酒成梦
醉酒成梦 2020-12-20 15:15

I have two jQuery mobile pages (#list and #show). There are several items on the #list page with different IDs. If I click on item no.5, the ID no5 will be stored in localSt

2条回答
  •  天命终不由人
    2020-12-20 15:44

    Disclaimer: This solution isn't official and only tested for demo, not for production.

    You can pass data between pages using $.mobile.changePage("target", { data: "anything" });. However, it only works when target is a URL (aka single page model).

    Nevertheless, you still can pass data between pages - even if you're using Multi-page model - but you need to retrieve it manually.

    When page is changed, it goes through several stages, one of them is pagebeforechange. That event carries two objects event and data. The latter object holds all details related to the page you're moving from and the page you're going to.

    Since $.mobile.changePage() would ignore passed parameters on Multi-page model, you need to push your own property into data.options object through $.mobile.changePage("#", { options }) and then retrieve it when pagebeforechange is triggered. This way you won't need localstorage nor will you need callbacks or setTimeout.

    1. Step one:

      Pass data upon changing page. Use a unique property in order not to conflict with jQM ones. I have used stuff.

      /* jQM <= v1.3.2 */
      $.mobile.changePage("#page", { stuff: "id-123" });
      
      /* jQM >= v1.4.0 */
      $.mobile.pageContainer.pagecontainer("change", "#page", { stuff: "id-123" });
      
    2. Step two:

      Retrieve data when pagebeforechange is triggered on the page you're moving to, in your case #show.

      $(document).on("pagebeforechange", function (event, data) {
      
        /* check if page to be shown is #show */
        if (data.toPage[0].id == "show") {
      
          /* retrieve .stuff from data.options object */
          var stuff = data.options.stuff;
      
          /* returns id-123 */
          console.log(stuff);
        }
      });
      

    Demo

提交回复
热议问题