Good day! I will continue to write articles about what I had to write on Backbone.js during the work and what you may encounter. Today we will talk about the asynchronous data download, or rather the data that we often need on the site.
Suppose you can add different types of data on the site (picture, text, audio), but these types can be expanded. Possible types are stored in the database. Every time to get from the base is very expensive. We need to get and use once.
So we load the data:
app.models.dataTypes = new DataTypesCollection(); app.models.dataTypes.fetch();
Now we show the user
app.models.dataTypes anywhere . But at us one puncture is possible, what if the user immediately goes to that page where we need this field? To do this, create an event that the data is received.
')
app.models.dataTypes = new DataTypesCollection(); app.models.dataTypes.fetch({ success: function() { Backbone.history.trigger("dataTypesLoaded"); } });
Now we need to “catch” this event. To do this, I wrote a function
loadDataTypes , which takes as a parameter the place where you need to
place the data (
place ). Because I have to display this block in several places on one page. (Adding and editing data occurs on one page).
function loadDataTypes(place) { place.empty();
Thus, we load data, for example, at the first load and then we give it out in the right places. We can call as much as necessary.
But if to speak generally, then we can have a large number of such fields. For all fields we write similar functions and all data will be loaded asynchronously with the output as it is loaded. The user will not even notice how quickly everything loaded.
From the pros, we got the fact that we only collect data from the server once and then use them as much as we want. Thereby not harming the user.
PS If you need a description of
SelectItemView , I can write, but everything is trivial there.