简体   繁体   中英

Backbone.js render().el Usage

I've got this piece of code from a Backbone.js tutorial from here . 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:

itemView.render().el

Could anybody explain me why the render() function is called with the .el part and why not just itemView.render() ?

Thank you for your time and help :-)

The render() call returns the itemView itself. It then asks for the el instance variable (the element itself), which is then appended to the list view. In essence, the list view includes all the elements of the items rendered individually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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