Search code examples
javascriptjqueryjsonbackbone.jsbackbone.js-collections

Why the 'fetch function' automatically call the 'parse function' on backbone.js collection?


I am trying to parse my json file into Backbone collection and model as like below.

This is .json file

[
{
    "type": "rect",
    "x": 10,
    "y": 10,
    "w": 100,
    "h": 100,
    "color": "red"
},
{
    "type": "arc",
    "x": 210,
    "y": 20,
    "w": 200,
    "h": 150,
    "color": "blue"
}
]

And I also have .html file as like below.

    <script>
    $(function() {
        var JSONModel = Backbone.Model.extend({});

        var MyCollection = Backbone.Collection.extend({
            model : JSONModel,
            url : 'profiles.json',
            initialize : function() {
                alert("init");
            },
            parse : function(response) {

                for (var i = 0; i < response.length; i++) {
                    var tmpModel = new JSONModel();
                    tmpModel.set({
                        type : response[i].type,
                        x : response[i].x,
                        y : response[i].y,
                        w : response[i].w,
                        h : response[i].h,
                        color : response[i].color
                    });
                    this.add(tmpModel);
                    alert("inserting" + i);
                }

                return response;
            }

        });

        var collection = new MyCollection();
        collection.fetch();
        alert(collection.length);


    });
</script>


Q.

1.In this code, why fetch function call parse function?

2.Is there any other function which is called from fetch function?

3.Do you think how can I fix this code to get the json object? I cannot get the 'collection.length' in this code.

Please help.


Solution

  • Please have a look at my comments below for your question:

    1. In this code, why fetch function call parse function?

    Ans: While extending Backbone.Collection you have overridden the parse callback function and Backbone internally calls the parse function whenever we try to fetch the collection. This is the standard call. I don't think you have to Or can change this behavior.

    2. Is there any other function which is called from fetch function?

    Ans: As far as I know I don't think any other callback function is getting called while calling fetch. Why you are looking for it? What is your requirement for this point? Any specific reason?

    3. Do you think how can I fix this code to get the json object? I cannot get the 'collection.length' in this code.

    Ans: You will have to wait till the time we receive the data and hence we need to add success handler in following way:

    collection.fetch({
      success: function(collection){
        // Callback triggered only after receiving the data.
        console.log(collection.length); 
      }
    });