Bind a view to collections in backbone.js

|▌冷眼眸甩不掉的悲伤 提交于 2020-03-22 08:51:10

问题


I'm semi-new to backbone. I'm trying to bind a collection to a view so that when a new model is added to a collection, the view is updated. I think when you do this with models you can bind to the model's change event. But how do you do the same with collections?

App.Views.Hotels = Backbone.View.extend({

    tagName: 'ul',

    render: function() {
        this.collection.each(this.addOne, this);
        var floorplanView = new App.Views.Floorplans({collection:floorplanCollection});
        $('.floorplans').html(floorplanView.render().el);
        return this;
    },

    events: {'click': 'addfloorplan'},

    addOne: function(hotel) {
        var hotelView = new App.Views.Hotel ({model:hotel});
        this.$el.append(hotelView.render().el);
    },

    addfloorplan: function() {
        floorplanCollection.add({"name": "another floorplan"});
    }
});

App.Collections.Floorplans = Backbone.Collection.extend({
    model: App.Models.Floorplan,
    initialize: function () {
        this.bind( "add", function() {console.log("added");} );
    }
});

The click event fires and adds to the collection. But how do I get it to update the view?


回答1:


You can listen to the collection's add event, which fires when a new item is added to the collection. In modern versions of Backbone, the method listenTo is preferred to bind or on for listening to events. (Read de documentation for more info)

For example, in your case this should do the trick:

App.Views.Hotels = Backbone.View.extend({

  initialize: function() {
    this.listenTo(this.collection,'add', this.addOne);
  },
  //rest of code

Hope this helps!




回答2:


Here is a nice tutorial I had followed long ago.

An Intro to Backbone.js: Part 3 – Binding a Collection to a View

It helps you define a DonutCollectionView that will, when given a collection of donuts, render an UpdatingDonutView for each donut.



来源:https://stackoverflow.com/questions/15299592/bind-a-view-to-collections-in-backbone-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!