简体   繁体   English

Backbone.js render()。el用法

[英]Backbone.js render().el Usage

I've got this piece of code from a Backbone.js tutorial from here . 我从这里获得了Backbone.js教程中的这段代码。 The code is as follows: 代码如下:

(function($){

    var Item = Backbone.Model.extend({
        defaults: {
            part1: 'Hello',
            part2: 'World'
        }
    });

    var ItemList = Backbone.Collection.extend({
        model: Item
    });

    var ItemView = Backbone.View.extend({
        tagName: 'li',

        initialize: function(){
            _.bindAll(this, 'render');
        },

        render: function(){
            $(this.el).html("<span>" + this.model.get('part1') + " " + this.model.get('part2') + "</span>");
            return this;
        }

    });

    var AppView = Backbone.View.extend({
        el: $('body'),

        initialize: function(){
            _.bindAll(this, 'render', 'addItem', 'appendItem');

            this.collection = new ItemList();
            this.collection.bind('add', this.appendItem)
            this.counter = 0;
            this.render();
        },

        events: {
            'click button#add': 'addItem'
        },

        addItem: function(){
            var item = new Item();
            item.set({
                'part2': item.get('part2') + this.counter++
            });
            this.collection.add(item);
        },

        appendItem: function(item){
            var itemView = new ItemView({
                model: item
            });
            $('#list', this.el).append(itemView.render().el);
        },

        render: function(){
            $(this.el).append("<button id='add'>Add Item</button>");
            $(this.el).append("<ul id='list'></ul>")
        },
    });

    var Tasker = new AppView();

})(jQuery);

There is one thing I could not understand from the above code. 从上面的代码中我无法理解一件事。 In the function appendItem there is this piece of code: 在函数appendItem有这段代码:

itemView.render().el

Could anybody explain me why the render() function is called with the .el part and why not just itemView.render() ? 有人可以解释为什么用.el部分调用render()函数,为什么不只是.el itemView.render()

Thank you for your time and help :-) 感谢您的时间和帮助:-)

The render() call returns the itemView itself. render()调用返回itemView本身。 It then asks for the el instance variable (the element itself), which is then appended to the list view. 然后它会询问el实例变量(元素本身),然后将其附加到列表视图中。 In essence, the list view includes all the elements of the items rendered individually. 实质上,列表视图包括单独呈现的项目的所有元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM