Backbone.js`listento`没有为过滤的集合触发

时间:2013-08-03 19:41:50

标签: backbone.js

listento仅触发全局集合,而不是我在创建时传递给视图的集合。

例如:

var MyView = Backbone.View.extend({
  initialize: function() {
    this.listenTo(notes, "add", this.test);  // <--- THIS FIRES
    this.listenTo(this.collection, "add", this.test); // <-- THIS DOES NOT FIRE
  },

  test: function() {
    console.log('model added to collection')
  }
});

我在创建视图时传递过滤后的集合:

var notesFilteredByGroup = notes.filter_group(123);
var myView = new MyView({
  collection: notesFilteredByGroup
});

这是Notes集合:

Notes = Backbone.Collection.extend({
  url: '/notes',

  model: Note,

  filter_group: function(groupNum) {
    filtered = this.filter(function(note) {
      return note.get('groupNum') === groupNum;
    });
    return new Notes(filtered);
  }
});

当我提交新笔记时,它会更新全局集合。如何告诉notesFilteredByIdthis.collection收听添加的模型?

编辑:

添加了请求的代码,更改了一些变量名称以使问题更清晰

注意提交代码:

var AddNoteView = Backbone.View.extend({
  tagName: 'div',

  template: _.template( AddNoteTemplate ),

  events: {
    'click #noteSubmitButton': 'submit'
  },

  initialize: function() {
    this.render();
  },

  render: function() {
    var template = this.template( this.model.toJSON() );
    this.$el.html(template);
    return this;
  },

  submit: function(event) {
    event.preventDefault();

    var newNote = {
      text: $('#text').val(),
      groupNum: $('#groupNum').val(),
    };

    this.collection.create(newNote, {wait: true});
  }
});

实例化AddNoteView:

var notes = new Notes;
notes.fetch();
var addNoteView = new AddNoteView({
  collection: notes
});

1 个答案:

答案 0 :(得分:3)

我认为初始化时你的notes全局集合看起来像这样

var notes = new Notes();

所以这会传递给不同的观点。

但是当你过滤集合时

   var notesFilteredById = notes.filter_id(123);

   ...
   return new Notes(filtered);

您将返回新笔记集合..

这将创建一个与全局notes.

具有相同绑定的新实例

为此,您必须明确地将创建的模型添加到过滤的集合中。

像这样的东西

// You need to pass that into the view
var addNoteView = new AddNoteView({
  collection: notes,
  filteredCollection : notesFilteredByGroup
});

在视图中,您需要将其明确添加到其他集合

var AddNoteView = Backbone.View.extend({
  tagName: 'div',

  template: _.template( AddNoteTemplate ),

  events: {
    'click #noteSubmitButton': 'submit'
  },

  initialize: function() {
    this.listenTo(this.collection, 'add', addToCollection);
    this.render();
  },

  render: function() {
    var template = this.template( this.model.toJSON() );
    this.$el.html(template);
    return this;
  },
  addToCollection : function(model) {
      // Need to add to the other collection.
      this.options.filteredCollection.add(model);
  },
  submit: function(event) {
    event.preventDefault();

    var newNote = {
      text: $('#text').val(),
      groupNum: $('#groupNum').val(),
    };

    this.collection.create(newNote, {wait: true});
  }
});