Reputation: 7734
I'm defining a list of dom elements as properties of a Backbone view object like so:
el : $("body"),
elTicket : $('#ticket'),
...
However, the dom that these jquery objects point to isn't generated yet.
What I used to do when this problem arose is to wrap the jquery object in a function and return it like so:
el : function(){
return $('body');
},
...
Which then results in an ugly line as such:
this.el().append('dasd');
Is there a better solution to this?
Upvotes: 1
Views: 152
Reputation: 5945
It's difficult to give a comprehensive answer without knowing the context, but I would encourage you to look at the problem from another angle.
In the case of the body tag, run your code after the body has been loaded into the DOM. You can either do this by placing your script tags at the end of your HTML file, or use one of those ifDocumentLoaded functions and call your backbone code within that.
If the main document is already loaded, and you just selected body as an example for your question - let's say that instead the tag is a div. You can call JQuery on an element that has not been loaded into the DOM. What happens is the that JQuery creates this element, but it is not attached to the DOM. You can later attach it when the opportunity is right - perhaps with a query method like $(body).append(this.el).
Note that the el property is by default a plain old DOM element that is expected to corresspond to the particular view. So you can have:
App.MyView = Backbone.View.extend({
tagName: 'table',
...
});
automatically you can access App.MyView.el. It will be an unattached DOM Element whose tag name is table. Now if you want to apply some Jquery magic to this DOM Element you can access it via App.MyView.$el
Upvotes: 1