I am storing all file uploads in progress, FileUploadProgressModel, on a Backbone collection, UploadProgressCollection. I have everything working except the this.$el
on my view, UploadPrograssView. I have initialized the $el
to <body>
tag of my page.
I want this.$el
to be the body element of my HTML page, instead it has a brand new <body>
HTMLElement. Now I can not access my upload progress bar element using this.$el
since this.$el
is not the <body>
tag I want. What causes this error?
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 });
You have to explicitly specify el
property for your View if you want the view to reference an element already existing in the DOM. If tagName
property is specified, a new element is created. See the docs for more details.
So you have to set el
to DOM selector string when you declare a View:
var UploadPrograssView = Backbone.View.extend({
el: "body",
...
});
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.