Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to append html elements to el in backbone.

I seem to have a problem with the code below. I have a div element with the id='content' in my html. I wanted to replace 'body' element of el property with the div element but my hello world text doesn't when I typed el: $('div') or el:$('div#content') or el: $('#content'). I'm a beginner in backbone.js and in my understanding, I believe that this el property holds our parent tag where all our templates will be added as child elements(in this case 'body' tag being parent and 'p' tag being child).

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

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

    render: function(){
        (this.el).append("<p>Hello World</p>");
    }
});

var listView = new ListView();
})(jQuery);
like image 854
jaykumarark Avatar asked Feb 19 '23 04:02

jaykumarark


1 Answers

The View.el property should be defined as a jQuery selector (string), not a reference to HTML element.

From Backbone documentation:

var BodyView = Backbone.View.extend({
  el: 'body'
});

Or as you wished,

el:'div#content'

When the view initializes, Backbone references the element in makes it available via the view.$elproperty, which is a cached jQuery object.

this.$el.append("<p>Hello World</p>");

The sample code you posted works, because there is always only one bodyelement, and that element already exists in the DOM when your view is rendered. So when you declare el:$('body'), you get a reference to the body element. The code in renderin works, because this.el is now a direct reference to the jQuery object:

(this.el).append("<p>Hello World</p>");

If you need to initialize a Backbone view using an existing DOM element (not a selector), Backbone documentation recommends passing it in the initialize function.

like image 138
jevakallio Avatar answered Feb 21 '23 01:02

jevakallio