gpt4 book ai didi

javascript - 添加新模型后渲染

转载 作者:行者123 更新时间:2023-12-03 09:33:48 24 4
gpt4 key购买 nike

我的服务器上有一些模型已经启动。它们已成功获取并渲染。但是当我保存新模型时,我无法渲染它。当我重新加载页面时 - 一切正常:呈现新添加的模型。如何快速渲染它(无需刷新页面)?

这是我的 ListView

var GroupView = Backbone.View.extend({
tagName: 'ul',

initialize: function () {
this.collection = new StudentsCollection();
// this.collection.on('add', this.render, this);
this.collection.on('update', this.render, this);
// this.collection.on('reset', this.render, this);
this.collection.fetch({
success: function () {
console.log('success!');
},
error: function (collection, response, options) {
console.log(options);
}
});
},

render: function () {
// this.$el.empty();
var self = this;

this.collection.each(function (student) {
var studentView = new StudentView({
model: student
});
self.$el.append(studentView.render().el);
});
$('.container').append(this.$el);
}
});

我尝试在集合上添加“添加”事件,但这只是所有内容的两倍。有什么想法吗?

最佳答案

在集合上使用 add 是正确的做法,因为您希望在添加模型时执行某些操作。您看到所有内容都是双重的原因(我怀疑除了最近添加的)是因为您的渲染函数只是附加到 $el

Backbone 不会在渲染之前清除现有 View ,您必须决定使用什么策略。

最简单的解决方案是简单地添加 this.$el.empty()render 的开始。我不建议这样做,因为每次添加模型时它都会重新渲染整个事物。

更好的解决方案是创建一个函数,仅将一个 View 添加到现有 View 中,并在 add 上触发该函数。

类似下面的内容

initialize: function() {
...
this.collection.on('add', this.addStudentView, this);
...
}

addStudentView: function(model) {
var studentView = new StudentView({
model: model
});
this.$el.append(studentView.render().el);
}

关于javascript - 添加新模型后渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31403181/

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