谁能告诉我如何在创建新模型时调用集合的 create
函数后重新获取 Backbone 集合?
当我在创建新模型后对我的集合调用 fetch
时,有时我会得到该模型,有时不会。
我的问题是当我在我的集合中创建一个新模型时,我没有取回我的模型的 id 然后我不能立即更新它,我需要刷新页面然后我得到了 id创建的模型。
我尝试使用 listenTo
但我无法使用它,因为我需要向一个函数发送更多集合。
我的引导模态视图在保存时创建了我的模型,它持久保存到数据库中,并且在创建它时我在控制台中获取了除模型 ID 之外的所有属性。
主干 View :
app.types.EditView = Backbone.View.extend({
tagName: "div",
$container: $('#containerEdit'),
template: _.template($('#itemEdit-template').html()),
events:
{
"click .save": "save",
},
initialize: function(options)
{
this.options = options;
this.$container.html(this.render());
this.start();
this.end();
},
render: function()
{
this.$el.html(this.template());
return this.$el;
},
save: function()
{
console.log("save");
$('#openModal').modal('hide');
var dan = this.model.dan_u_tjednu_usera.datum;
var mjesec = this.model.dan_u_tjednu_usera.mjesecBrojevi;
var godina = this.model.dan_u_tjednu_usera.godina;
var start = $("#start").val();
var end = $("#end").val();
var user_id = this.model.user.id;
this.model.shifts.create({day: dan, month: mjesec, year: godina, time_from: start, time_to: end, user_id: user_id});
this.options.model.el.html($("<td href='#openModal' width='25%' align='center' class='list-group test' scope='row'>" + start + " - " + end + " " + "Admin" + "</td>"));
this.model.shifts.fetch({sync: true});
console.log("test", this.model.shifts);
}
在这里您可以看到,在我的回复中,我在创建时没有获得 id 属性。
在这里你可以看到,当我点击我的单元格时,我记录了我的收藏,但我在这里没有创建模型的 id 属性。当我登录 this.model 时,我也没有得到它的 id 属性
最佳答案
这是因为调用Collection.create
时向服务器发送的请求是异步的,Javascript代码会在服务器收到并响应请求之前继续执行。
如果您想要使用从服务器返回的 ID 更新模型,您可以在 Collection.create
调用中指定 {wait: true}
。这意味着集合将不会立即添加模型,而是仅在服务器响应(成功)时添加。
在这种情况下,您不应该在之后立即运行fetch
,因为它还需要等待创建操作完成。您应该设置任何以下操作以在创建操作完成时触发。这是一个例子:
var model = collection.create({field: 'abc'}, {wait: true});
model.once('sync', function() { window.alert(model.id); });
关于javascript - 集合创建后如何重新获取 Backbone 集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40305477/