在绑定Backbone.js的视图到集合 [英] Bind a view to collections in backbone.js

查看:209
本文介绍了在绑定Backbone.js的视图到集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是半新的骨干。我想,这样,当一个新的模式被添加到一个集合,该视图更新到集合绑定到一个视图。我认为,当你这样做配车型可以绑定到模型的更改事件。但你如何使用集合做?

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?

推荐答案

您可以收听到集合的添加事件,当增加一个新的项目而火灾到集合。在骨干的现代版本,该方法 listenTo 是pferred到绑定 $ P $或收听活动。 (阅读更​​多信息德文档)

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

希望这有助于!

这篇关于在绑定Backbone.js的视图到集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆