簡體   English   中英

bone.js this.model是未定義的wine應用程序示例

[英]backbone.js this.model is undefined wine application example

我是第一次學習骨干js,並嘗試使示例wine應用程序正常工作,它從數據庫中正常運行,列表視圖顯示了用戶列表,但是當它調用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”); 在初始化函數中,但沒有區別。

在路由器中,您僅執行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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM