I have the following code:
$(document).ready(function() {
$('.container').ready(function() {
var v = new Video($(this));
v.load();
});
});
How can I keep v from disposing itself? The initialized class loads 3 variables: video, source and controls. When a click or event listener calls its function and tries to access any of them it cannot, because they have since been destroyed.
How can I get around this problem?
More sample code:
$.Class('Video', {
init: function(container) {
this.video = container.find('.video');
this.source = this.video[0];
this.controls = {
// ...
total: container.find('.total'),
buffered: container.find('.buffered')
};
},
load: function() {
this.source.addEventListener('progress', function() {
var buffered = Math.floor(this.source.buffered.end(0)) / Math.floor(this.source.duration);
this.controls.buffered.width(Math.floor(buffered * this.controls.total.width()));
}, false);
}
});
Variables in JavaScript are function scoped, so when the callback function passed to $(‘.container’).ready() exits, the variable you declared in that function, v, is out-of-scope and eligible for garbage collection.
One way to avoid that is to declare a global variable and store your Video object in that. For example:
Of course, global variables are at least as much trouble in JavaScript as in any other language (maybe more). A best-practice is to declare exactly one global variable, an object, for your entire page/application and store any and all of your persistent data within that object. You want to give this lone global a name that is likely to be unique, so that it won’t conflict with any third-party scripts you may use. I like to use the convention used with Java namespaces of using a registered domain name associated with the work as the unique identifier. So if you or your employer owns the domain name examplename.com:
Elsewhere in your code, access the video objects like so: