Question

I have a view I want to insert into the DOM. As I understand it, the setElement method creates a jQuery element (saved as $el) which is unattached to the DOM. I'm trying to insert that jQuery element into an existing DOM element, without success.

SimpleView = Backbone.View.extend({

    initialize: function(){
        this.setElement('#simpleview');
        this.render();
    },

    render: function(){
        this.$el.appendTo('#container');
    }
});

var myview = new SimpleView();

What am I missing?

jsFiddle here

Was it helpful?

Solution

I think you misunderstand how setElement works. When you call setElement, you're supposed to give it a DOM element that already exists and then setElement does three things:

  1. Sets the view's el to the element.
  2. Undelegates the events from the old el and binds the view's events to the new el.
  3. Caches a jQuery wrapped version of el in $el.

You seem to be calling setElement to try to create a new element with id="simpleview". You probably just want to include id: 'simpleview' in the view definition since

this.el is created from the view's tagName, className, id and attributes properties, if specified. If not, el is an empty div.

You should get what you're looking for if your view looks more like this:

SimpleView = Backbone.View.extend({
    id: 'simpleview',
    initialize: function(){
        this.render();
    },
    render: function(){
        this.$el.appendTo('#container');
    }
});

Updated fiddle: http://jsfiddle.net/ambiguous/7GPEy/

OTHER TIPS

This should do what you're after:

$(function(){

    var SimpleView = Backbone.View.extend({

        el: $('#container'),

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

        render: function () {
            this.$el.html('<div>HELLO</div>');
        }

    });

    var myview = new SimpleView();

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top