Backbone / Underscore查看错误

时间:2014-08-26 15:36:25

标签: jquery backbone.js underscore.js backbone-views

我有以下代码。目标是提交GET请求并显示结果。当我运行它时,我看到在控制台中返回了以下JSON。

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

同时我收到错误'TypeError:n is undefined'。我无法弄清楚我做错了什么。此外,这是实现我的目标或更好的方法的最有效方式吗?感谢。

<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>

1 个答案:

答案 0 :(得分:1)

this.users.fetch()

fetch是一个异步函数。请求完成后,结果将通过其回调方法提供:

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