简体   繁体   中英

Why doesn't my “el” work in Backbone?

define([
    'jquery',
    'underscore',
    'backbone',
    'text!modules/index/templates/container.html'
], function($, _, Backbone, container_temp){
    var indexView = Backbone.View.extend({
        el: $('.main_container'),
        initialize:function(){
            _.bindAll(this, 'render');
        },
        render:function(){
            var $this = this;
            var $el = this.el;
            $.get('/js/index/render', {}, function(data){
                var dat = JSON.parse(data);
                $this.pars = dat;
                var tpl = _.template(container_temp, dat);
                $el.html(tpl);
            });
        }
    });
    return new indexView;
});

Running this code is supposed to fill $el with HTML. However, my browser messes up at $el.html(tpl); .

Uncaught TypeError: Object #<HTMLDivElement> has no method 'html' 

To fix this, I have to do: $($el).html(tpl); so that jquery registers.

This seems awkward. In my past projects, I have always done it the former way, and it has always worked.

this.el is a raw DOM element but the html method belongs to jQuery.

Try var $el = this.$el; in your render method:

render:function(){
    var $this = this;
    var $el = this.$el;
    $.get('/js/index/render', {}, function(data){
        var dat = JSON.parse(data);
        $this.pars = dat;
        var tpl = _.template(container_temp, dat);
        $el.html(tpl);
    });
}

if you look at your render function:

render:function(){
        var $this = this;
        var $el = this.el;
        $.get('/js/index/render', {}, function(data){
            var dat = JSON.parse(data);
            $this.pars = dat;
            var tpl = _.template(container_temp, dat);
            $el.html(tpl);
        });
    }

You explicitly assign var $el so the following $el equals this.el which is the raw dom element without the jQuery wrapper you usually get with $el.

Try this: this.$el without the var declaration .

So to get the $el into the $.get scope the code would look like:

render:function(){
    var $this = this;
    var element = this.$el;
    $.get('/js/index/render', {}, function(data){
        var dat = JSON.parse(data);
        $this.pars = dat;
        var tpl = _.template(container_temp, dat);
        element.html(tpl);
    });
}

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