First I create some backbone views:
(function() {
var SomeView = Backbone.View.extend({ ... });
// finally on ready
$(function() {
// init my view
var v = new SomeView({...});
});
})();
Now, as we can see, I am instantiating the view inside the jQuery ready function, and assigning the instance to a local variable, which will be lost once the function exits. But, I notice that my view just works perfectly — i.e., even though I am losing the reference to the view, it just works.
I guess this is because there are many closures involved, and all the required variables are actually preserved inside those closures.
So, my question is: is this alright to instantiate the views like this. Is it OK to not save the reference to it.
If you never need a reference to the view again, this is totally fine. You can render the view after instantiating it (or even do it in its constructor) and it will insert the generated HTML in the DOM (depending on the options you have set on the view).
Of course if you need to call some view methods later from some code outside the view you will need to keep a reference to the view around somewhere.