Backbone fetch() success callback doesn't work

25,789

BackboneJS fetch delegates to sync. sync returns a jqXHR object for your own use.

You could just:

Todos.fetch({
    success: function(){
            $("#app").show();
            $(".loader").hide();
        }
}).always(function() { $(".loader").hide() });

You can read more about it in this blog post.

Apart from that, make sure that your server returns a valid json when the collection is empty. If the response is not a valid json you will get a failure.

Share:
25,789
Apoorv Parijat
Author by

Apoorv Parijat

Updated on January 04, 2020

Comments

  • Apoorv Parijat
    Apoorv Parijat over 4 years

    In my app, there are different user accounts. What I'm trying to do is, show a loader.gif till the time .fetch() is fetching the content from resource url + rendering the views and hide the loader when fetching is done.

    Now, when a user logs in, his list of TODO items is fetched by Todos.fetch and on success callback, loader.gif fades out.

    $("#app").hide();
    $(".loader").show();
    Todos.fetch({
        success: function(){
                $("#app").show();
                $(".loader").hide();
            }
    });
    

    This works fine for all user except those which have no Todo items. For these users, success callback is not triggered and loader.gif stays. Is there any other way to hide the loader.gif?


    It seems to me that success function is called only when even a single model is added to the collection. If there is nothing to add to the collection, success isn't called.

  • Apoorv Parijat
    Apoorv Parijat over 11 years
    Great find :) Thanks a ton and am using Rails which takes care of most of the things.
  • Micros
    Micros about 10 years
    Nice find! But keep in mind it does not provide the (model, response, options) arguments that you would expect in the success-callback. So you have to find another way to access the model again, if that's what you were doing in your success-callback.