Answer the question
In order to leave comments, you need to log in
How to change model in subview in Backbone?
Hello. How to work with the model when there are subviews in the view. Here's what I mean:
I have a component, let it be some kind of abstract voting. It consists of a counter and a comment form.
Here is a conditional picture:
I want to put the form in a separate view.
var VoteForm = Backbone.View.extend({
});
var Vote = Backbone.View.extend({
initialize: function () {
this.form = new VoteForm();
}
});
var VoteModel = Backbone.Model.extend({
defaults: {
count: 0,
comment: ''
}
});
var VoteForm = Backbone.View.extend({
events: {
'submit': function () {
this.model.save({comment: this.commentValue}) // this.commentValue - это то что введено в форму
}
}
});
var Vote = Backbone.View.extend({
initialize: function () {
this.form = new VoteForm({
model: this.model
});
}
});
var vote = new Vote({
model: new VoteModel
});
var VoteForm = Backbone.View.extend({
events: {
'submit': function () {
this.trigger('submit', {comment: this.commentValue}) // this.commentValue - это то что введено в форму
}
}
});
var Vote = Backbone.View.extend({
initialize: function () {
this.form = new VoteForm();
this.form.on('submit', function (data) {
this.model.save({
comment. data.comment
})
});
}
});
var vote = new Vote({
model: new VoteModel
});
Answer the question
In order to leave comments, you need to log in
In general, it is best to follow the rule "One model - one view". In your case, this is the first option. Then the older view Vote
will play the role of a layout. Provided that you should not smear the model into two views.
In general, there is a decent amount of material on working with nested views in the backbone. Marionette.js even has ready-made entities for your case: Region
and LayoutView
.
I can be wrong, but it seems to me that it is worth highlighting the subview if you reuse it in another place. Therefore, I would proceed from how it would be more convenient to use it in other places.
If I use a subview in other places, I would use a callback, if only in one view, then the model would pass.
I wonder how you ended up deciding.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question