【发布时间】:2016-05-05 03:49:07
【问题描述】:
在我的 Backbone 视图中,我希望能够立即将我的模型添加到我的集合中,并在新创建的模型中包含 'id' 属性。换句话说,我需要立即访问这个'id'。在id 可用的情况下,我的removeCategory 方法可以工作。为了“解决”这个问题,我尝试在this.collection.add(model); 正下方添加this.collection.fetch() 行,但它给了我非常糟糕的用户界面(新的<li> 甚至不会渲染等),而且看起来非常糟糕无论如何编码练习。
我对 Backbone 比较陌生,所以我不确定 create(保存/添加)是否应该使用 id 自动将模型添加到集合中。如果应该,那么我从 Rails RESTful API 接收的 JSON 数据一定有问题。如果create 不这样做,那么我怎样才能通过id 立即访问这个特定的新创建模型(除了刷新浏览器——呃!)?一旦我调用“addCategory”方法,我就需要在我的 Handlebars 模板中为<li data-id={{id}}></li> 提供id。
另外(这可能是一个相关的问题),当我执行model.fetch(); 时,我会取回模型的整个集合,以及没有id 的新创建的服务器端模型。对此的任何帮助将不胜感激。
window.CategoriesView = Backbone.View.extend({
index_template: HandlebarsTemplates['categories/index'],
events: {
'click .delete': 'removeCategory',
'click .category_add': 'addCategory'
},
initialize: function() {
_.bindAll(this, 'render');
this.collection.fetch();
this.listenTo(this.collection, 'all', this.render);
},
show: function() {
$("#categorymodal").modal();
},
addCategory: function(e) {
e.preventDefault();
// I wrote the next three lines here explicitly rather than using 'create'
var model = new Category({ name: $(this.el).find('.category_name').val() });
model.save();
this.collection.add(model);
this.show();
},
removeCategory: function(e) {
e.preventDefault();
var id = $(e.target).parents('li').data('id');
var model = this.collection.where({ id: id })[0];
this.collection.remove(model);
if (model) { model.destroy(); }
this.render();
},
render: function() {
$(this.el).html(this.index_template());
this.collection.models.forEach(function(cat) {
var li_template = HandlebarsTemplates['categories/show']
$(this.el).find('.categories').append(li_template({
id: cat.toJSON().id,
name: cat.toJSON().name
}));
}, this);
return this;
}
});
这是我在 Rails 中的#create 操作....
def create
@category = Category.create(category_params)
render :nothing => true
end
我正在使用jbuilder 提供来自 Rails API 的 JSON。
这是我的 Backbone 模型和收藏...
window.Category = Backbone.Model.extend({
urlRoot: "categories"
});
window.Categories = Backbone.Collection.extend({
model: Category,
url : function() {
return 'categories';
}
});
【问题讨论】:
标签: ruby-on-rails backbone.js handlebars.js fetch