参考“这个”背景之外的模型

时间:2013-12-10 03:53:57

标签: javascript jquery backbone.js backbone-views

我正在尝试在我视图中不在当前“this”上下文中的事件上设置listenTo。

在我的“评论”视图中我有:

var app = app || {};

app.CommentView = Backbone.View.extend({

  tagName: 'div',

  template: _.template( $('#comment-template').html() ),

  // "<event> <selector>" : "<method>" aka function defined below
  events: {
    'click .up' : 'addUpVote',
    'click .down' :'subtractUpVote',
    'click .destroy_comment' : 'removeOneComment',
    'click .destroy-vote' : 'destroyVote'
  },

  initialize: function() {
    this.render();
    this.listenTo(app.Vote, 'add', this.render); // THIS DOESN'T WORK
    this.listenTo(this.model,'change', this.render);
    this.listenTo(this.model, 'destroy', this.remove);
  },

  render: function() {
    this.$el.html( this.template( this.model.toJSON() ) );
    this.$el.find('#vote-buttons').html();//(PASS IN VOTE TEMPLATE//);
    this.$el.attr('comment_id', this.model.get('id'));

    return this;
  },

removeOneComment: function() {
    this.model.destroy();
  },

voteAttributes: function() {
  return {
    comment_id: this.model.get('id'),
    };
  },

addUpVote: function( event ) {
  var vote = new app.Vote(this.voteUpAttributes());
  vote.save({
    success: function (vote) {
      vote.toJSON();
    }
  });
},

voteUpAttributes: function() {
  return {
    comment_id: this.model.get('id'),
    upvote: 1
  };
},

subtractUpVote: function ( event ) {

  var vote = new app.Vote(this.voteDownAttributes());
  vote.save({
    success: function (vote) {
      vote.toJSON();
    }
  });
},

voteDownAttributes: function() {
  return {
    comment_id: this.model.get('id'),
    downvote: -1
  };
}

});

如果您在我的addUpVote函数中注意到我创建了一个新的投票模型(app.Vote创建了一个新模型)。每当发生变化(创建或更改新的投票模型)时,我想重新渲染评论视图。

如何在我的初始化函数中设置listenTo以在app.Vote模型上查找事件?我想像

this.listenTo(app.Vote, 'add', this.render);
//instead of this.model 'app.Vote' because this.model is referring to the comment model.

我的方法是否正确?如果有人有任何建议我会很感激,谢谢!

1 个答案:

答案 0 :(得分:3)

如果我理解正确,您正在模拟模型上的添加事件,那么您的方法似乎不正确。

将模型添加到集合时会触发“add”事件(模型没有add事件,集合也没有。)

backbone documentation:“添加”(模型,集合,选项) - 将模型添加到集合中。

因此,您可以拥有一个投票集合,并监听该集合上的添加事件,当您将投票模型添加到投票集合时会触发该事件。

因此,您可以收听模型与服务器成功同步时触发的“同步”事件,而不是收听模型所没有的“添加”事件。但是这仍然不起作用,因为您正在模型定义(app.Vote)上侦听事件而不是在使用该定义创建的实例上。代码中的实例将是var 投票 = new app.Vote(this.voteDownAttributes());.因此,如果您为投票创建一个集合,则需要在该集合的实例上侦听“添加”事件,而不是集合定义。

另一种方法是在addUpVote和subtractUpVote方法的save方法的成功回调中调用this.render()(这不是最好的方法,但它现在可能会起作用)。在您的代码中可能看起来像这样:

addUpVote: function( event ) {
  var self = this;
  var vote = new app.Vote(this.voteUpAttributes());
  vote.save({
    success: function (vote) {
      vote.toJSON();
      self.render();
    }
  });
},