Search code examples
backbone.jsbackbone-views

backbone js view how to display


I am new to backbone js and somehow i managed to read the json file and get the data to the controller. Now how do i pass the data to my view. I am ok if the data is displayed with ul tags.All i want is to display the data from json file.

(function($){
var model = Backbone.Model.extend({});
        collection = Backbone.Collection.extend({
            url:'services.json',
            model:model,
            parse:function(response){    
                console.log(response.values); //Working
                return response.values;
            }
        });

     var ListView = Backbone.View.extend({
    el: $('body'), // attaches `this.el` to an existing element.

initialize: function(){
  _.bindAll(this, 'render'); // fixes loss of context for 'this' within methods

   this.render(); // not all views are self-rendering. This one is.
},

     render: function(eventName) {
        _.each(this.model.models, function(){

            $(this.el).append();  //How to display the values here

       }, this);



          return this;
        }

  });

source = new collection();
var listView = new ListView({model:source});
 source.fetch({
    success: function (values) {
        var data = values.toJSON();
        console.log(data); //Working
        listView.render();
    }
});

 })(jQuery);

json

{
    "values": [
        {
            "name": "name A",
            "location": "location A"
        },
        {
            "name": "name B",
            "location": "location B"
        }
    ]
}

Solution

  • There are multiple issues in your code

    1) you shouldn't pass collection as model, change to

    var listView = new ListView({collection:source});
    

    2) dont call render multiple times, it should called after ajax so remove render from view's initialize

    initialize: function(){
      _.bindAll(this, 'render'); // fixes loss of context for 'this' within methods
    },
    

    3)appending to dom

        render: function(eventName) {
                this.collection.each(function(model) {
                 this.$el.append('li'+model.get('name');+'<li>');
            }
       }