문제

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

도움이 되었습니까?

해결책

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/

다른 팁

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

});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top