0

I am still using backbonejs since find it extremely easy and fast to bootstrap new micro API based website.

Question is about best practice when it comes to collection loading and rendering upon the collection group click.

Lets say i have static list of brands. On click on the brand I initiate fetching of the collection and upon fetch end successful I render the collection.

The problem happens when the user click on the brands not having the previous click processed, so what happens is that there are 2 collections og both brands loaded and rendered. What is the best way to deal with this in order to "cancel" or just ignore the first fetch and only render the last one that user clicked?

I found the solution is just deactivate the brand list until the request is processed, but it annoying UX wise because user might want to click right away on another one not waiting for the results (if he miss-clicked for example)

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Max
  • 43
  • 1
  • 4
  • 1
    Backbone works best when every part of an app is a component. It shouldn't cause a problem to load 2 collections at the same time. Though, without a [mcve], we can't judge your solution. – Emile Bergeron Jan 30 '17 at 18:51
  • Also, If you would like tips on how to improve a working code snippet, take a look at [codereview.stackexchange.com](http://codereview.stackexchange.com/). – Emile Bergeron Jan 30 '17 at 19:06

1 Answers1

0

The underlying xhr object returned from Backbone.fetch has the ability to cancel the current request, xhr.abort() .

When the user clicks and the collection fetches, save the return value.

var xhr = myCollection.fetch()

The xhr has properties that tell you the current status of the request.

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState

If the user clicks again and causes the collection to fetch while another request is still processing, simply ask the xhr if it's in the middle of a request. If it is, abort, and continue with your current fetch, and reassign the xhr object.

Sample code:

function userClickedSomething(){
    if(xhr.readyState > 0 && xhr.readyState < 4)
        xhr.abort()
    xhr = myCollection.fetch()
}

How you store a reference to the xhr object is up to you.

More details: Is it possible to stop Backbone "read" requests

Community
  • 1
  • 1
Eric Guan
  • 15,474
  • 8
  • 50
  • 61
  • The underlying xhr is a [`jqXHR`](http://api.jquery.com/jQuery.ajax/#jqXHR) which exposes `readyState` for backward compatibility with a `XMLHttpRequest`. It implements the [Promise](http://api.jquery.com/Types/#Promise) interface which offers a better alternative to check the state of the request: [`.state()`](http://api.jquery.com/deferred.state/). It will return string to compare against, instead of magic numbers like `readyState`. – Emile Bergeron Jan 31 '17 at 14:53