最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Not able to append html elements to el in backbone. - Stack Overflow

programmeradmin1浏览0评论

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);

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);
Share Improve this question asked Dec 13, 2012 at 7:09 jaykumararkjaykumarark 2,4496 gold badges36 silver badges54 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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 remends passing it in the initialize function.

发布评论

评论列表(0)

  1. 暂无评论