Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone parsing json response

I've been using Backbone for a total of 3 days now, and I can see that this has been asked about quite a lot, but honestly I'm just not getting it. I've been banging my head against the wall trying to get a basic app running parsing nested json and I just can't seem to work it out. It all works if I flatten out the json response, and remove the nested elements, but that's not how I will receive it.

I've tried some examples with Backbone relational, but I'm really stuck here, a total backbone n00b, and hoping for some help.

Here is the HTML:

<div id="employee-data">
    <script type="text/template" id="employees-template">
        <ol id="data-block">
        </ol>
        <div class="clear"></div>
    </script>
    <script type="text/template" id="employee-template">
        <h2>Your employer: <span><%= employerName %></span> </h2>
        <div>Employee Id: <span><%= employeeId %> </span></div>
        <div>Name: <span><%= employeeName %>     </span></div>
        <div>Title: <span><%= employeeJobTitle %> </span></div>
        <div>Location: <span><%= employeeLocation %> </span></div>
    </script>
</div>

Here is the js:

var Contact = {
    Models: {},
    Collections: {},
    Views: {},
   Templates:{}
}

Contact.Models.Employee = Backbone.RelationalModel.extend({});

Contact.Collections.Employees = Backbone.Collection.extend({
    model: Contact.Models.Employee,
    url: "includes/test-data.json",

    initialize: function(){
        console.log("Employees initialize");
    }
});

Contact.Templates.employees = _.template($("#employees-template").html());

Contact.Views.Employees = Backbone.View.extend({
    el: $("#employee-data"),
    template: Contact.Templates.employees,

    initialize: function () {       
       this.collection.bind("reset", this.render, this);
       this.collection.bind("add", this.addOne, this);
    },

    render: function () {
        console.log("render")
        console.log(this.collection.length);
        $(this.el).html(this.template());
        this.addAll();      
    },

    addAll: function () {
       console.log("addAll")
       this.collection.each(this.addOne);
    },

    addOne: function (model) {
       console.log("addOne")
       view = new Contact.Views.Employee({ model: model });
       $("ol", this.el).append(view.render());
    }

})


Contact.Templates.employee = _.template($("#employee-template").html());

Contact.Views.Employee = Backbone.View.extend({
    tagName: "li",
    template: Contact.Templates.employee,

    initialize: function () {
        this.model.bind('destroy', this.destroyItem, this);
        this.model.bind('remove', this.removeItem, this);
    },

    render: function () {
        return $(this.el).append(this.template(this.model.toJSON())) ;


    }
})


Contact.Router = Backbone.Router.extend({
    routes: {
        "": "defaultRoute"
    },

    defaultRoute: function () {
        console.log("defaultRoute");
        Contact.employees = new Contact.Collections.Employees();

        new Contact.Views.Employees({ collection: Contact.employees }); //Add this line

        Contact.employees.fetch({
        error:function(response, xhr){
            console.log(response);
            console.log(xhr)
        },
        success:function(){
            console.log("success");
        }
    });
        console.log(Contact.employees.length)
    }
})

var appRouter = new Contact.Router();

Backbone.history.start();

And finally the json:

[
    {
  "contactId" : "345345234",
  "employees" : [ {
    "employeeId" : "EE-00000001",
    "employeeName" : "BubbA Ho-tep",
    "employeeLegalFirstName" : "Bubba",
    "employeePrefFirstName" : "",
    "employeeLastName" : "Ho-tep",
    "employeeMaritalStatus" : "Single",
    "employeeBirthYear" : "1942",
    "employeeJobTitle" : "",
    "employmentStatus" : "Active",
    "employmentTerminationDte" : "",
    "employeeReferenceCode" : "EE1",
    "employeeDivision" : "HR",
    "employeeLocation" : "Downtown",
    "employeeEmail" : "[email protected]",
    "employer" : {
      "employerId" : "ER-00000001",
      "employerName" : "Initech"
    }
  } ]
}
]
like image 291
retsoced Avatar asked Nov 06 '12 19:11

retsoced


1 Answers

You should use the parse() method in your collection :

Contact.Collections.Employees = Backbone.Collection.extend({
    model: Contact.Models.Employee,
    url: "includes/test-data.json",

    initialize: function(){
        console.log("Employees initialize");
    },

    parse : function(response){
        return response.employees;  
   }    

});

There is one parse() in the MOdel as well as in the Collection, for the same purpose on url() handling.

EDIT : I'm not an expert in the Router, but I suppose you have to render the View at some point.

var view = new Contact.Views.Employees({ collection: Contact.employees }); 
view.render();
like image 63
Nicolas Zozol Avatar answered Sep 27 '22 22:09

Nicolas Zozol