Reputation: 45081
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.
Upvotes: 1
Views: 1337
Reputation: 638
Your understanding is correct, if you do not need to call this view from the outside, then of course you do not need to record this reference. However, your example is too simple, the actual situation of general need to record this reference. btw:There are a lot of backbone of best practice, and I hope useful for you: http://ricostacruz.com/backbone-patterns
Upvotes: 0
Reputation: 1410
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.
Upvotes: 1