brins0
brins0

Reputation: 325

Backbone fetch failure notification

We're having an issue with our backbone application. We want to provide a user with a notification when a fetch fails (timeout or general error), but we want to display a dialog over the previous page's content rather than showing an error message in the new page (how Facebook/LinkedIn etc. do it)

To trigger a request for the new content, we have to navigate to the new URL first. We can't really change this without a rework, so we want to avoid this if possible. What we need to do is send the user back to the previous URL when there is a connection error, which would cause the route to fire, re-requesting the previous content. We really want to avoid doing this however.

We're aware that we can send a user back using a navigate without triggering a route, but this will mess up the browser history, making backwards become forwards in this case. We could also force a browser back, keeping the history trail correctly, but this would force a re-fetch of the content.

We've also investigated setting a flag of some kind telling our router not to re-request data on the next route change, but this would cause issues when browser back is used to go to a previous screen on which the fetch fails. In this instance we'd need to send the user 'forwards' in their journey instead. As far as we know, this isn't possible using the browser's history manager.

Is there any way of having a dialog how we want, or will we have to go the same way as Facebook/LinkedIn and co.?

Upvotes: 0

Views: 1606

Answers (1)

StuR
StuR

Reputation: 12238

Do you have an example of your code / what you have tried?

Going off what you have said, if there is an error fetching the model data after your URL has changed you can silently redirect the user back to the previous URL using the router, e.g:

window.product_v = Backbone.View.extend({
    render: function() {
        this.model.fetch({
            processData: true,
            data: this.model.attributes,
            success : function(d){
            },
            error : function(d) {
                MyRouter.previous();
            }
        })
    }
});

Then in your router could keep an array of your history so that the route isn't 'triggered' on redirect. or by simply doing:

Backbone.history.navigate(route, {trigger: false, replace: true});

The below question/answer describes this perfectly:

Silently change url to previous using Backbone.js

class MyRouter extends Backbone.Router
    constructor: (options) ->
        @on "all", @storeRoute
        @history = []
        super options

    storeRoute: ->
        @history.push Backbone.history.fragment

    previous: ->
        if @history.length > 1
            @navigate @history[@history.length-2], true 

Upvotes: 1

Related Questions