参照“;这个“;上下文

Referring to a model outside of "this" context

本文关键字:上下文 这个 参照      更新时间:2024-05-20

我正在尝试为一个不在当前视图中"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会创建一个新模型)。每当发生更改(创建或更改新的Vote模型)时,我都希望重新呈现Comment View。

我该如何在初始化函数中设置listenTo来查找应用程序上的事件。投票模型?我觉得有点像

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

我在这方面的做法正确吗?如果有人有任何建议,我将不胜感激,谢谢!

如果我理解正确,您正在侦听模型上的add事件,因此您的方法似乎不正确。

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

从主干文档中:"add"(模型、集合、选项)--当模型添加到集合中时。

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

因此,您可以收听模型与服务器成功同步时触发的"同步"事件,而不是收听模型没有的"添加"事件。但这仍然不起作用,因为你在听模型定义(app.Vote)上的事件,而不是在用该定义创建的实例上。代码中的实例将是varvote=新应用程序。投票(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();
    }
  });
},