骨干视图有错误

时间:2017-03-17 08:01:48

标签: javascript jquery backbone.js

我正在Backbone集合UploadProgressCollection上存储正在进行的所有文件上传,FileUploadProgressModel。除了我的视图上的this.$el,UploadPrograssView之外我还能正常工作。我已初始化了网页的$el<body>标记。

我希望this.$el成为我的HTML网页的正文元素,而不是它有一个全新的<body> HTMLElement。现在我无法使用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 });

1 个答案:

答案 0 :(得分:2)

如果您希望视图引用DOM中已存在的元素,则必须显式为View指定el属性。如果指定了tagName属性,则会创建 new 元素。有关详细信息,请参阅the docs

因此,在声明View:

时,必须将el设置为DOM选择器字符串
var UploadPrograssView = Backbone.View.extend({ 
    el: "body",
    ...
});