3

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);
  }
});

当我提交新笔记时,它会很好地更新全局集合。我如何告诉notesFilteredByIdorthis.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
});
4

1 回答 1

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});
  }
});
于 2013-08-03T19:57:58.297 回答