我开始使用Backbone.js并尝试构建我的第一个示例应用程序 – 购物清单.
我的问题是,当我获取项目集合时,重置事件可能不会被触发,因此我的render方法不会被调用.
模型:
Item = Backbone.Model.extend({ urlRoot : '/api/items',defaults : { id : null,title : null,quantity : 0,quantityType : null,enabled : true } });
采集:
ShoppingList = Backbone.Collection.extend({ model : Item,url : '/api/items' });
列表显示:
ShoppingListView = Backbone.View.extend({ el : jQuery('#shopping-list'),initialize : function () { this.listenTo(this.model,'reset',this.render); },render : function (event) { // console.log('THIS IS NEVER EXECUTED'); var self = this; _.each(this.model.models,function (item) { var itemView = new ShoppingListItemView({ model : item }); jQuery(self.el).append(itemView.render().el); }); return this; } });
列表项视图:
ShoppingListItemView = Backbone.View.extend({ tagName : 'li',template : _.template(jQuery('#shopping-list-item').html()),// set template for item render : function (event) { jQuery(this.el).html(this.template(this.model.toJSON())); return this; } });
路由器:
var AppRouter = Backbone.Router.extend({ routes : { '' : 'show' },show : function () { this.shoppingList = new ShoppingList(); this.shoppingListView = new ShoppingListView({ model : this.shoppingList }); this.shoppingList.fetch(); // fetch collection from server } });
申请开始:
var app = new AppRouter(); Backbone.history.start();
解决方法
这是你的问题:
“当模型数据从服务器返回时,它使用set来(智能地)合并获取的模型,除非你通过{reset:true}”Backbone Docs
因此,您希望使用重置选项触发提取:
this.shoppingList.fetch({reset:true}); // fetch collection from server
另外,您可以定义a collection attribute on a view:
this.shoppingList = new ShoppingList(); this.shoppingListView = new ShoppingListView({ collection : this.shoppingList // instead of model: this.shoppingList });
原文地址:https://www.jb51.cc/js/155955.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。