0

我第一次学习主干 js 并试图让示例葡萄酒应用程序正常工作,它从数据库中提取,并且列表视图显示用户列表,但是当它调用 WineDetails 时会抛出错误。

这是代码:

// Models
window.Wine = Backbone.Model.extend();

window.WineCollection = Backbone.Collection.extend({
  model:Wine,
  url:"../api/users"
});


// Views
window.WineListView = Backbone.View.extend({

  tagName:'ul',

  initialize:function () {
    this.model.bind("reset", this.render, this);
  },

  render:function (eventName) {
    _.each(this.model.models, function (wine) {
        $(this.el).append(new WineListItemView({model:wine}).render().el);
    }, this);
    return this;
  }

});

window.WineListItemView = Backbone.View.extend({

  tagName:"li",

  template:_.template($('#tpl-user-list-item').html()),

  render:function (eventName) {
    $(this.el).html(this.template(this.model.toJSON()));
    return this;
  }

});

window.WineView = Backbone.View.extend({

  template:_.template($('#tpl-user-details').html()),

  render:function (eventName) {
    $(this.el).html(this.template(this.model.toJSON()));
    return this;
  }

});


// Router
var AppRouter = Backbone.Router.extend({

  routes:{
    "":"list",
    "users/:id":"wineDetails"
  },

  initialize:function () {
    this.wineList = new WineCollection();
    this.wineListView = new WineListView({model:this.wineList});

  },

  list:function () {
    this.wineList.fetch();
    $('#sidebar').html(this.wineListView.render().el);
  },

  wineDetails:function (id) {
    this.wine = this.wineList.get(id);
    this.wineView = new WineView({model:this.wine});
    $('#content').html(this.wineView.render().el);
  }
});

var app = new AppRouter();
Backbone.history.start();

和html

<div id="header"><span class="title">Backbone Cellar</span></div>

<div id="sidebar"></div>

<div id="content">
  <h2>Welcome to Backbone Cellar</h2>
  <p>
  This is a sample application part of of three-part tutorial showing how to build a CRUD    application with Backbone.js.
  </p>
</div>

<!-- Templates -->
<script type="text/template" id="tpl-user-list-item">
  <a href='#users/<%= user_id %>'><%= user_id %></a>
</script>

<script type="text/template" id="tpl-user-details">
<div class="form-left-col">

  <label>Name:</label>
  <input type="text" id="user_id" name="user_id" value="<%= user_id %>" required/>

</div>

</script>

</div>

和萤火虫中的错误

TypeError: this.model is undefined
$(this.el).html(this.template(this.model.toJSON()));

我试过添加 _.bindAll(this,"render"); 在初始化函数中,但没有区别。

4

1 回答 1

0

在你的路由器中你只做 wineList.fetch()。

您需要处理成功回调,如下所示

wineList.fetch({success: function(){
    $("#content").html(new WineListView({model: wineList, page: p}).el);
}});

我在 github 中使用骨干网和 requirejs 实现了示例 winecellar 项目。 https://github.com/phillycoder/backbone-require-cellar

于 2013-01-03T16:14:52.947 回答