gpt4 book ai didi

javascript - Backbone js显示旧模型

转载 作者:行者123 更新时间:2023-12-03 08:56:06 25 4
gpt4 key购买 nike

我是主干新手,现在主干 js 和backbone.validation 遇到问题。这是我的代码:

var EmployeeCreateView = Backbone.View.extend({
el: "#page_content",

initialize: function() {
console.log("initializing....");
this.model = new EmployeeModel();
console.log(this.model);
this.render();
},

render: function() {
Backbone.Validation.bind(this);

this.$el.html(EmployeeCreateTemplate);
},

events: {
"click #submit-employee": "submitEmployee"
},

submitEmployee: function(e) {
e.preventDefault();
var data = Backbone.Syphon.serialize(this);

this.model.set(data, { validate: true });
console.log(this.model);
if (!this.model.isValid()) {
_.each(this.model.validationError, function (error) {

});
} else {
this.model.save(null, {
success: function() {
new EmployeeCollectionView();
},
error: function(model, response) {
this.$el.html(ErrorTemplate)({
error: response.responseText
});
}
});
}
}
});

发生的情况是,当我进入此页面时,console.log() 都显示一个模型,这一切都很好。但是当我离开页面并再次返回时,初始化中的 console.log() 显示一个模型,这就是我想要的。但是,submitEmployee() 函数上的 console.log 显示两个模型。这是控制台输出:

// first page load, shows a single object
initializing....
n {cid: "c2", attributes: Object, _changing: false, _previousAttributes: Object, changed: Object…}
// other page load
[n, n, n, n, n]
// back to original page, shows a new object
initializing....
n {cid: "c10", attributes: Object, _changing: false, _previousAttributes: Object, changed: Object…}
// submit still sees both objects, which i don't want
n {cid: "c2", attributes: Object, _changing: false, _previousAttributes: Object, changed: Object…}
n {cid: "c10", attributes: Object, _changing: false, _previousAttributes: Object, changed: Object…}

有人可以告诉我我做错了什么吗?

谢谢!

最佳答案

你有僵尸对象 - 应该被清理的对象,但由于引用而徘徊,并稍后弹出来咬你。

部分问题在于您管理 View 的方式。让 View 渲染本身是一个坏主意。让一个 View 创建一个 subview 来呈现自身以替换当前 View 是一个更糟糕的主意。您看到的问题是此代码结构的直接结果。

我建议从两篇文章开始:

managing page transitions in Backbone.js

Making workflow explicit in JavaScript

关于javascript - Backbone js显示旧模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32499063/

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