How to re-render partial of model in backbone?
Asked Answered
E

1

9

I have a answers list like below:

enter image description here

each list item is a backbone model.

{
  title: 'answer title...',
  content: 'answer content...',
  voteStatus: 'up'
}

When I click up-vote or down-vote, The model's voteStatus will be change, and this answer item be re-render.

If there have a picture in answer's content, the picture will be re-render too, But this is not what I want.

How could I just re-render the vote button when I just change voteStatus?

Estellaestelle answered 12/4, 2014 at 14:11 Comment(0)
A
7

Have a subview inside your AnswerView that is only responsible for rendering the voting arrows, VotingArrowsView. You would initialize this subview inside the initialize function of AnswerView and then prepend the subview's el to the parent view's el when rendering the parent view:

var AnswerView = Backbone.View.extend({
  initialize: function(options){
    this.template = _.template($('#answerTmpl').html());
    this.votingArrowsView = new VotingArrowsView({ model: this.model });
    ...
  },
  render: function(){
    this.$el.html(this.template(this.model.toJSON()));
    this.$el.prepend(this.votingArrowsView.render().el);
    return this;
  },
  ...
});

var VotingArrowsView = Backbone.View.extend({
  initialize: function(options){
    this.template = _.template($('#votingArrowsTmpl').html());
    this.listenTo(this.model, 'change:voteStatus', this.render);
  },
  render: function(){
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  }
});
Acetometer answered 14/4, 2014 at 16:42 Comment(3)
But I have another question, I think i could move voteButton's click events(click voteUp and voteDown) frome AnswerView to VotingArrowsView. when I do this and click the button, it's not work. It seems like the event listening is broken. Could you tell me why?Estellaestelle
I use this.delegateEvents(); in VotingArrowsView when render. All done! thanks :)Estellaestelle
shouldn't there be var AnswerView = Backbone.View.extend({ instead of var AnswerView = Backbone.Model.extend({ ?Masonmasonic

© 2022 - 2024 — McMap. All rights reserved.