问题
I have two views -- an OverlayView and a StoryView. The StoryView needs to get appended to the OverlayView (both are created dynamically). I create the #overlay div dynamically in the OverlayView, but when I set the 'el' of the StoryView to #overlay, this.$el of StoryView is an empty array. The #overlay div definitely exists in the DOM by the time the StoryView is created.
How do I get the StoryView to recognize the dyanmically created #overlay as its 'el'? Am I correct in assuming the 'el' should be the 'parent' container to which the view is appended? Should the 'el' of the OverlayView actually be '#overlay'?
OverlayView:
OverlayView = Backbone.View.extend({
el: $('body'),
events: {
'click #film': 'hideOverlay'
},
initialize: function() {
this.render();
},
render: function() {
this.$el.append('<div id="overlay"></div>');
return this;
}
});
StoryView:
var StoryView = Backbone.View.extend({
el: $('#overlay'),
events: {
'click .close': 'closeStory'
},
initialize: function() {
this.render();
},
render: function() {
console.log(this.$el); // Returns empty array []
return this;
}
});
回答1:
Your problem is that your StoryView
el
should simply be a selector — not a jQuery object. That will cause Backbone to try to retrieve the object (which does not yet exist) at the time you specify el
. Just change el: $('#overlay')
to el: '#overlay'
. You might also do the same for $('body')
in your first view, since it's not necessary. Just always use selectors instead of jQuery objects and you'll be fine.
Working example here.
来源:https://stackoverflow.com/questions/10142451/how-do-you-create-backbone-views-with-an-el-that-was-dynamically-created