I'm new to backbone and now having a problem with backbone js and backbone.validation. Here is my code:
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
});
}
});
}
}
});
What happens is when I go to this page both console.log() display one model, that's all good. But when I leave the page and come back again the console.log() in the initialize shows one model, wich is what i want. But the console.log on the submitEmployee() function displays two models. Here is the console output:
// 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…}
Can anybody please tell me what I am doing wrong?
Thanks!
You have zombie objects - objects that should have been cleaned up, but are hanging around due to references, and popping up to bite you later.
Part of the problem is the way you're managing views. Having a view render itself is a bad idea. Having a view creating a child view that renders itself to replace the current view is an even worse idea. The problems you're seeing are a direct result of this code structure.
I'd recommend two articles to start:
managing page transitions in Backbone.js
and