我正在通过一个教程来学习如何使用backbone.js,并且很难理解骨干的视图如何“看到”该系列。

以下是视图代码,下面是收集代码。

我可以看到,变量$专辑正在分配给元素内的特定类'.albums',但我不明白该代码如何引用“ this.collection”。

视图和集合都从标准的骨干和骨干。收集类扩展。只是从看着它,我看不到他们什至彼此之间的存在。我假设“ this”一词是指LibraryView的这个特定实例。

我想这是我的主要问题:

代码如何 collection = this.collection 能够看到外部收藏吗?

// A wrapper view to display each album in Library
    window.LibraryView = Backbone.View.extend({         
        tagName: 'section',
        className: 'library',

        initialize: function() {
            _.bindAll(this, 'render');
            this.template = _.template($('#library-template').html());
            this.collection.bind('reset', this.render);
        },

        render: function() {            
            var $albums,
                collection = this.collection;           

            $(this.el).html(this.template({}));
            $albums = this.$('.albums');
            collection.each(function(album) {
                var view = new LibraryAlbumView({
                    model: album,
                    collection: collection
                });
                $albums.append(view.render().el);
            });
            return this;
        }

    });

这是专辑集:

// Albums Collection
    window.Albums = Backbone.Collection.extend({
        model: Album,
        url: '/albums'
    })

编辑:


我想我在这里的帮助下找到了它:

还有另一个代码创建库变量,并将其分配给新专辑集合:

window.library = new Albums();

另外,在路由器中,有一个初始化语句通过“库”变量传递:

initialize: function() {
            this.libraryView = new LibraryView({
                collection: window.library
            });

现在似乎更有意义。 :)

只是发布此内容,以防其他人像我一样困惑。

有帮助吗?

解决方案

一个集合必须传递给LibraryView构造函数。例如,

myLibrary = new LibraryView({
  collection: new Albums()
})

但是,这里发生了重要的魔术。一切传递给视图构造函数最终都进入了视图的 options 财产。但是,选择数量的属性,请复制到视图本身。所以你可以说 this.collection 代替 this.options.collection.

这些特殊属性是:

'模型',“集合”,“ el”,“ id”,“属性”,“ className”,“ tagName”

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top