Backbone 视图有错误的 el

Backbone view has wrong el

我正在将所有正在进行的文件上传 FileUploadProgressModel 存储在 Backbone 集合 UploadProgressCollection 中。在我的视图 UploadPrograssView 中,除了 this.$el 之外,我的一切正常。我已经将页面的 $el 初始化为 <body> 标签。

我希望 this.$el 成为我的 HTML 页面的正文元素,而不是它有一个全新的 <body> HTML 元素。现在我无法使用 this.$el 访问我的上传进度条元素,因为 this.$el 不是我想要的 <body> 标签。是什么导致了这个错误?

var FileUploadProgressModel = Backbone.Model.extend({
    initialize : function(){
        this.on("change:loaded_size", function(){
            this.set("progress", 100 * this.get("loaded_size") / this.get("total_size"));
        });
    },
    defaults : {
        progress : 0,
        total_size: 1,
        loaded_size : 0,

    }
});
var UploadProgressCollection = Backbone.Collection.extend({
    model: FileUploadProgressModel,
    initialize : function(){
    this.on("update", function(){
        // View already registered to this event
    });
},
});


var UploadPrograssView = Backbone.View.extend({ 
    tagName : "body",
    initialize : function(){
        _.bindAll(this, "render");
        this.model.bind('change', this.render);
        this.render();
    },
    render : function(){

        var total_loaded_size = 0;
        var total_file_upload_size = 0;
        tracker.forEach(function(model){
            if(!isNaN(model.get("loaded_size"))) total_loaded_size += model.get("loaded_size");
            if(!isNaN(model.get("total_size"))) total_file_upload_size += model.get("total_size");
        });

        var progress = parseInt(total_loaded_size / total_file_upload_size * 100, 10) + '%';

        //TODO bad way of doing things. I want to user this.$el but it has lost the actual referance to the body instread it has this new HTML element "<body><body>"
        $('.progress .progress-bar').css(
                'width',
                progress
                );
        return this;
    }
});


var tracker = new UploadProgressCollection();
var trackerView = new UploadPrograssView({model : tracker });

如果您希望视图引用已经存在于DOM.如果指定 tagName 属性,则会创建一个 new 元素。有关详细信息,请参阅 the docs

所以你必须在声明视图时将 el 设置为 DOM 选择器字符串:

var UploadPrograssView = Backbone.View.extend({ 
    el: "body",
    ...
});