Have view listen to collection event

前端 未结 3 1817
情话喂你
情话喂你 2021-02-04 12:53

I have a view myView and a collection myCollection. When I add a model to myCollection, the add event is trigger

3条回答
  •  野性不改
    2021-02-04 13:18

    You can pass the collection to the view when you instantiate it, and then you can have the view bind to the add event on the collection in the initialize method.

    Here's a code example

    MyView = Backbone.View.extend({
      initialize: function() {
        this.collection.bind('add', this.onModelAdded, this);
      },
    
      ...other view functions
    
      onModelAdded: function(addedModel) {
        //do something
      }
    }
    

    And this is how you pass the collection in when you instantiate the view

    var view = new MyView({ collection: myCollection });
    

提交回复
热议问题