Asynchronous data loading Backbone.js

    Good afternoon! I will continue to write articles about what you had to write on Backbone.js in the course of work and what you may encounter. Today we will talk about asynchronous data loading, or rather the data that we often need on the site.

    Suppose you can add different types of data on a site (picture, text, audio), but these types can expand. Possible types are stored in the database. Each time, getting from the base is very expensive. We need to get it and use it once.

    So we load the data:

    app.models.dataTypes = new DataTypesCollection();

    Now we show app.models.dataTypes to the user anywhere . But we can have one puncture, what if the user immediately goes to the page where we need this field? To do this, create an event that the data is received.

    app.models.dataTypes = new DataTypesCollection();
    	success: function() {

    Now we need to "catch" this event. To do this, I wrote the loadDataTypes function , which takes as a parameter the place where the data should be placed ( place ). Because I have to display this block in several places on one page. (Adding and editing data takes place on one page).

    function loadDataTypes(place) {
    	place.empty(); // очищаем место
    	var addDataTypes = function() { // функция добавления данных
    		_.each(app.models.dataTypes.models, function(item) {
    			item.set("value", item.get("data_type_code"));
    			item.set("text", item.get("data_type_name"));
    			var selectItem = new SelectItemView({ // вид для optionа
    				el: place,
    				model: item
    			selectItem.render(); // выдаем
    	if (app.models.dataTypes.models.length != 0) { // если загружены
    	} else { // еще не загружены, "ловим" событие.
    		Backbone.history.on("dataTypesLoaded", addDataTypes); 

    Thus, we load data, for example, at the first load and then issue it in the right places. We can call any number.

    But speaking generally, 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 loads. The user will not even notice how quickly everything loaded.

    From the advantages, we got that we take data from the server only once and then use them as much as we want. Thus, without harming the user.

    PS If you need a description of SelectItemView , write, I can add, but everything is trivial there.

    Also popular now: