gpt4 book ai didi

javascript - 保存模型后无法重新渲染主干 View

转载 作者:行者123 更新时间:2023-11-27 23:31:30 26 4
gpt4 key购买 nike

我保存模型,并从服务器端得到数据库已更新的良好响应。我想做的是重新获取集合并使用保存的模型信息更新 View 。我错过了一些小事,但我就是无法弄清楚。

   $(document).ready(function () {
window.App = {
Models: {},
Collections: {},
Views: {}
};

window.template = function(id){
return _.template( $('#' + id).html() );
};


// Person Model
App.Models.Person = Backbone.Model.extend({
defaults: {
id: null,
question: null,
quizid: null,
answerid: null
},
url: function() {
return 'myurl/';
}
});


App.Collections.People = Backbone.Collection.extend({
model: App.Models.Person,
url: 'myurl/'

});



App.Views.People = Backbone.View.extend({
tagName: 'ul',

render: function(){
this.collection.each(function(person){
var personView = new App.Views.Person({ model: person });
this.$el.append(personView.render().el);
}, this);

return this;
}
});


App.Views.Person = Backbone.View.extend({
tagName: 'li',
template: template('personTemplate'),
events: {
"click #saveButton" : "savedata",
},


savedata: function(event){
//alert(this.model.get("id") + " " + $('#title').val());
var newModel = new App.Models.Person();
newModel.save({id: this.model.get("id"), question: $('#title').val()}, {
wait : true,
success: function (response) {
alert(response.responseText);
},
error: function (model, response) {
alert(response.responseText);
}
}
);
},

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



var peopleCollection = new App.Collections.People;
peopleCollection.fetch({
success: function(){
var peopleView = new App.Views.People({collection: peopleCollection});
$('body').append(peopleView.render().el);
}});


var pw = new peopleView({collection: personCollection});
pw.render();

最佳答案

如果您想在编辑模型数据后刷新 View ,则必须监听 syncchange 事件并重新渲染 View 。

App.Views.Person = Backbone.View.extend({
initialize: function(params) {
this.listenTo(this.model, 'sync', this.render);
}
});

如果您要添加全新模型,则需要在创建后立即将其添加到集合中。

newModel.save({id: this.model.get("id"), question: $('#title').val()} //...
this.collection.add(newModel)

并在人物 View 中监听add事件

this.lisenTo(this.collection, 'add', this.render

App.Views.People = Backbone.View.extend({
initialize: function(params) {
this.listenTo(this.collection, 'add remove sync', this.render);
},

render: function(){
this.$el.empty();

this.collection.each(function(person){
var personView = new App.Views.Person({ model: person });
this.$el.append(personView.render().el);
}, this);

return this;
}
});

在这种情况下,重新获取整个集合是多余的。

关于javascript - 保存模型后无法重新渲染主干 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34539492/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com