簡體   English   中英

為什么我的“ el”不能在Backbone中工作?

[英]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;
});

運行此代碼應該用HTML填充$ el。 但是,我的瀏覽器弄亂了$el.html(tpl);

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

要解決此問題,我必須做: $($el).html(tpl); 這樣jQuery注冊。

這看起來很尷尬。 在我過去的項目中,我一直都是以前一種方式完成的,並且一直都有效。

this.el是原始DOM元素,但html方法屬於jQuery。

嘗試var $el = this.$el; 在您的渲染方法中:

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

如果您查看渲染功能:

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

您顯式分配了var $el因此以下$ el等於this.el,這是原始dom元素,而沒有通常使用$ el獲得的jQuery包裝器。

試試這個: this.$el不帶var declaration

因此,要使$ el進入$ .get范圍,代碼應類似於:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM