Backbone.js progress bar while fetching collection

前端 未结 6 643
既然无缘
既然无缘 2021-02-09 10:43

i\'d like to show a progress bar while i update the app with fresh content. I guess the best thing to do would be to do it while calling .fetch on a collection.

The cont

6条回答
  •  终归单人心
    2021-02-09 11:26

    Here's some steps that might work out.

    1. when the fetch starts (maybe using ajaxStart or whatever), bring up your pop-over.
    2. when the fetch finishes, identify or create the image urls from the JSON and use one of the several image preloaders out there that have a callback whenever all the images are loaded. If you want to make that yourself, I'd say this would be the psuedocode for that:
      1. Push all your images to an array imagesurls. (this will be an array of strings).
      2. Capture the array length into a variable imagesleft.
      3. Create a function var imageOnLoad = function () {...} capturing that variable which
        1. decrements imagesleft by 1
        2. Does whatever it needs to to update the popover
        3. if imagesleft reaches 0, invoke the code/method to cause the popover to eventually go away
      4. For each of the strings imagesurls[i] in the imagesurls array
        1. create a new Image object. var img = new Image();
        2. img.onload = imageOnLoad;
        3. img.src = imagesurls[i];

    Of course I'm ignoring error situations (Images have an onerror property you could assign similarly and the original ajax could fail). but I think the gist of a solution is there. The only thing I'm wondering about is whether or not you actually need to keep a reference to each of the images objects as they're being created. It might be a good idea, at least until you are done with the whole image set. Otherwise, I'd have to worry about garbage collection somehow interfering in some implementation... but then maybe I'm just being paranoid.

提交回复
热议问题