Reputation: 320
How can i fetch the model only once and keep it for rendering with different conditions?
define(
["backbone", "jquery", "app/config", "app/TemplateManager", "app/User"],
function(Backbone, $, config, TemplateManager, User) {
var HeaderView = Backbone.View.extend({
tagName: "div",
className: "window-header",
User: new User,
events: {
},
initialize: function() {
var User = this.User;
if(!(this.model instanceof Backbone.Model)) {
this.model = User;
}
this.listenTo(Backbone, "dialog:open", this.dialogOpen);
this.listenTo(Backbone, "contacts:open", this.contactsOpen);
this.listenTo(Backbone, "window:close", this.restoreDefaults);
this.restoreDefaults();
// this.render();
},
render: function() {
var self = this;
TemplateManager.get("window-header", function(template) {
self.model.validate();
self.$el.html(template(self.model.toJSON()));
$("#window").prepend(self.$el);
});
return this;
},
dialogOpen: function(contact) {
this.model.set(contact.attributes);
this.render();
},
contactsOpen: function() {
if(!this.User.has("id")) {
var self = this;
this.User.fetch({
success: function(model, response, options) {
self.model.set(self.User.attributes);
self.render();
}
});
} else {
this.model.set(this.User.attributes);
this.render();
}
},
restoreDefaults() {
this.model.set(this.User.defaults());
this.render();
},
});
return HeaderView;
}
);
So in my application it should be 3 states of WindowHeader
I don't whant to fetch User data every time is it posible to do it once and store it in some variable? But when I call restoreDefaults() every time my this.User also cleared to default. Why? Why this.User equals to this.model? Even if I do this
var User = this.User;
this.model = User;
Is it equal?
this.model = this.User
I suppose doesn't. Am I wrong? What can I do?
Upvotes: 0
Views: 78
Reputation: 201
You this.model
and User
is the same object(the same reference).
The good practice is that that you no need to keep User
in this View. No need to do this User: new User
.
No need to set new data to model this.model.set(this.User.defaults());
I think you shouldn't mutate User model. If need you can create another model and don't touch User Model directly.
NOTE: new HeaderView({model: User})
. model param is special option, if passed, will be attached directly to the view. So you can access in view this.model
Upvotes: 1
Reputation: 320
I got it! I have to clone for get new model instance
this.model = this.User.clone();
Upvotes: 0