Backbone:多个视图订阅单个集合的事件?这是一种不好的做法吗?

时间:2012-04-26 20:42:41

标签: design-patterns backbone.js javascript javascript-framework

我有一个问题,我认为是非常基本的东西,但是:

我只看到了一个集合视图和单个视图依赖于正在更新的集合的示例。如果您有多个视图尝试订阅集合事件,例如reset,addOne,addAll等,该怎么办...

我是否错过了关于做/不这样做的一些观点?你有这方面的例子吗?这甚至有意义吗?

任何信息都非常感谢

    var Coll = Backbone.Collection.extend({
        model: SingleModel,
        url: 'service',
        initialize: function(){
            console.log('collection inited')

        }        

    });

    var SingleModel = Backbone.Collection.extend({});            

    var CollView = Backbone.View.extend({                
        el: 'ul',
        template: Handlebars.compile(someContainerTemplate),
        init: function(){
            _.bindAll(this, 'render', 'addAll', 'addOne');
            this.collection.bind("reset", this.addAll);

            this.collection.fetch();
        },
        render: function(){
            $(this.el).append(this.template())
        },

        addAll: function(){
            this.collection.each(this.addOne);
        },

        addOne: function(model){
            var view = new SingleView({ model: model })            
        }
    })

    var SingleView = Backbone.View.extend({
        tagName: "li",
        events: {
            "click .delete": "remove"                    
        },
        template: Handlebars.compile(someTemplateForSingleItem),  
        initialize: function() {
        _.bindAll(this,'render');

            this.model.bind('save', this.addOne);
            this.model.bind('destroy', removeEl);
        },

        remove: function(){
          this.model.destroy();  
        },

        removeEl: function(){
          $(this.el).remove();  
        },

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


    // standard so far (excluding any bad practices), 
    // but what if you have another view dependent on 
    // say the number of length of the collection, and 
    // you want it to update if any single models are destroyed

    var HeaderView = Backbone.View.extend({
        tagName: "div#header",
        template: Handlebars.compile(someHeaderTemplate), 
        initialize: function() {
        _.bindAll(this,'render');

        this.model.bind('save', this.addOne);
        },

        render: function() {
            //assigning this collection length

            var context = this.collection.length;
            return $(this.el).append(this.template(context));
        },      
    });        

    var coll = new Coll();
    new CollView({ collection: coll });
    new HeaderView({ collection: coll});

2 个答案:

答案 0 :(得分:30)

您正在做的事情非常好,也是使用Backbone的部分原因。来自Backbone introduction

  

每当UI操作导致模型的属性发生变化时,模型都会触发“更改”事件;显示模型状态的所有视图都可以通知更改,

请注意,他们说“所有视图”,而不是“视图”。

单个集合的多个视图的一个示例是聊天系统。假设您有一组在线用户;那么你可能在标题中有一个简单的视图,显示在线人数和另一个列出用户的视图(同一集合):

var User = Backbone.Model.extend({});
var OnlineUsers = Backbone.Collection.extend({
    model: User
});

var CounterView = Backbone.View.extend({
    tagName: 'span',
    initialize: function() {
        _.bindAll(this, 'render');
        this.collection.on('add', this.render);
        // other interesting events...
    },
    render: function() {
        this.$el.text(this.collection.size());
        return this;
    }
});
var ListView = Backbone.View.extend({
    initialize: function() {
        _.bindAll(this, 'render');
        this.collection.on('add', this.render);
        // other interesting events...
    },
    render: function() {
        var html = this.collection.map(function(m) {
            return '<p>' + m.get('name') + '</p>';
        });
        this.$el.html(html.join(''));
        return this;
    }
});

然后你有一个OnlineUsers个实例,但CounterViewListView个实例都会看到它。当人们上线或下线时,两个视图都将根据需要进行更新。

简单演示:http://jsfiddle.net/ambiguous/eX7gZ/

上面的示例情况听起来就像你正在做的事情,这正是Backbone的用途。干得好。

答案 1 :(得分:2)

我们遇到了同样的问题。我们需要为每个模型使用多个jQuery模板和唯一的内部事件,而不使用多个持有者视图。这是我们提出的解决方案:

var myHolderView = Backbone.View.extend({
    el: '#views',
    render: function(){
        // This is because 'this' change inside the collection.each
        var $this = this;

        // If you want a wrapper template
        var wrapperHtml = $('#view-wrapper-template').tmpl();
        $this.$el.append(wrapperHtml);
        $wrapper = $this.$el.find('> div'); // If wrapper is a div


        $this.collection.each(function(model){
            // Render and append the viewA with internal events
            var viewA = new myViewA({model: model});
            viewA.render();

            // Use this to add the views content (viewA.el) to this views element ('#views')
            //$this.$el.append(viewA.el);

            // Use this to add the view content (viewA.el) to this views wrapper element ($wrapper)
            $wrapper.append(viewA.el);


            // Render and append the viewB with internal events
            var viewB = new myViewB({model: model});
            viewB.render();
            //$this.$el.append(viewB.el);
            $wrapper.append(viewB.el);


            // Add more views here...
        });
    }
});

完整的来源和工作示例: http://jsfiddle.net/HLv5z/9/