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?

Robin
  • 634
  • 1
  • 7
  • 18

1 Answers1

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;
  }
});
Mehdi
  • 7,204
  • 1
  • 32
  • 44
idbehold
  • 16,833
  • 5
  • 47
  • 74
  • 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? – Robin Apr 19 '14 at 03:05
  • 1
    I use `this.delegateEvents();` in `VotingArrowsView` when `render`. All done! thanks :) – Robin Apr 19 '14 at 03:15
  • shouldn't there be `var AnswerView = Backbone.View.extend({` instead of `var AnswerView = Backbone.Model.extend({` ? – Mehdi Jun 05 '15 at 11:54