Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to re-render partial of model in backbone?

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?

like image 548
Robin Avatar asked Apr 12 '14 14:04

Robin


1 Answers

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;
  }
});
like image 78
idbehold Avatar answered Nov 06 '22 10:11

idbehold