为什么我点击用户的所有模型而不是单击的模型?

时间:2016-07-20 11:49:41

标签: javascript backbone.js

单击集合中的一个模型,即可获得该用户控制台中的所有模型,而不是单击的模型。任何人都可以帮助我吗?

App.js

在App.js中将模型发送到另一个视图以为每个模型创建一个独特的视图

var App = Backbone.View.extend({

    initialize: function() 
    {
            this.collection = new Documents();
            console.log("this.collection init", this.collection);
            this.listenTo(this.collection, 'add', this.render);
            this.listenTo(this.collection, 'sync', this.renderSidebarModels);
    },

    renderSidebarModels: function() 
    {
            console.log("renderSidebarModels SYNC", this.collection);

            for(var i=0; i<this.collection.length; i++)
            {
                    console.log(this.collection.models);
                    this.sidebar = new SidebarView({model: this.collection.models[i]});
            }                      
    },

    $( document ).ready(function() {
       console.log( "ready!" );
       var app = new App();
    });

SidebarView.js

在SidebarView.js中

我从集合中获取所有模型。当我点击id为#titles的按钮时,我会获取该用户的所有模型,而不仅仅是该模型上的点击模型。

var SidebarView = Backbone.View.extend({

        el : this.$("#sidebar"),

        template: _.template(this.$('#sidebar-template').html()),

        events: 
        {
                "click #titles": "open",
        },

        initialize: function() 
        {
                console.log("sidebarView.initialize", this.model);
                this.render();
        },

        render: function() 
        {

                this.$el.append(this.template({ users: this.model }));
                //console.log(this.model);
                //return this;
        },

        open: function(e) 
        {
                console.log("open.sidebarView", this.model);  
        },  

})

1 个答案:

答案 0 :(得分:2)

您的方法不是初始化模型视图的最简洁方法,因为您为每个模型初始化一个视图,但是您将视图分配给模型的方式是遍历集合模型,并将每个集合项分配给特定视图。这种方法很麻烦,导致性能损失,并且还会导致在视图中编写大量额外代码。

最好的方法是使用每个模型一个视图,这意味着我们集合中的每个模型都有自己的视图对象来呈现该模式的数据。但是,这并不需要使用View对象来迭代集合并填充列表。它仅将每个单独模型的实现移动到该模型的View。通过这种方法,每个视图都可以直接参考他们的模型。

这样的事情:

var App = Backbone.View.extend({    

    initialize: function() {
        this.collection = new Documents();
        console.log("this.collection init", this.collection);
        this.listenTo(this.collection, 'add', this.render);
        this.listenTo(this.collection, 'sync', this.renderSidebarModels);
    },

    renderSidebarModels: function(item) {
        this.collection.models.each(function(item) {
            var sidebarView = new DealerView({                    
                model : item
            }, this);

            sidebarView.render();
            _this.$el.append(sidebarView.$el);
        });
    }
});

使用您的方法获取点击项目的一种方法是使用数据属性:

open: function(e){
    e.preventDefault();
    var id = $(e.currentTarget).data("id");
    var item = this.collection.get(id);
    console.log(item);
},

但正如我所说,这个解决方案不是最好的解决方案,我们不得不根据模型的ID来查找模型。

阅读本文以便更好地理解:https://lostechies.com/derickbailey/2011/10/11/backbone-js-getting-the-model-for-a-clicked-element/