Search code examples
jquerybackbone.jsunderscore.jsbackbone-views

Backbone/Underscore View Error


I have the following code. The goal is to submit a GET request and display the results. When I run this I see the following JSON being returned in the console.

[{"name":"John Doe","email":"johndoe@backbone.com"},{"name":"John 
Hancock","email":"johnhancock@backbone.com"}]

At the same time I get an error 'TypeError: n is undefined'. I can't figure out what I am doing wrong. Also, is this the most efficient way to accomplish my goal or there a better method? Thanks.

<script type="text/template" id="form_template">
<input type="button" id="search_button" value="Go" />
</script>

<script type="text/template" id="iterator">
<ul>
<% _.each(value, function(user)  { %>
  <li><%= user.get("name") %></li>
  <li><%= user.get("email") %></li>
<% }); %>
</ul>
</script>

<div id="form_container"></div>
<div id ="iterator_container"></div>

<script type="text/javascript">

var UserModel = Backbone.Model.extend({
    urlRoot: 'http://localhost/backbone/users',
});

var UserModels = Backbone.Collection.extend({
    url: 'http://localhost/backbone/users',
    model: UserModel
});

FormView = Backbone.View.extend({
    el: '#form_container',
     initialize: function(){
        this.render();
    },
    render: function(){
        var template = _.template( $("#form_template").html(), {} );
        this.$el.html( template );
    },
    events: {
        "click input[type=button]": "doGET"
    },
    doGET: function( event ){
    var iterator_view = new IteratorView();
   }
 });

 IteratorView = Backbone.View.extend({
     el: '#iterator_container',
     initialize: function(){
     var self = this;
     self.users= new UserModels(); 
     self.users.fetch({
          success: function (model, response, options) {
          self.render();
       }
     });
    },
    render: function(){
        var template = _.template( $("#iterator_template").html(), {value:   
        this.users.models} );
        this.$el.html( template );
    },
 });

 var form_view = new FormView();
 </script>

Solution

  • this.users.fetch()
    

    fetch is an asynchronous function. The result will be available when the request is finished, through its callback method:

    initialize: function(){
        var self = this;
        self.users= new UserModels(); 
        self.users.fetch({
            success: function (model, response, options) {
                self.render();
            }
        });
    },