How do you create Backbone views with an 'el' that was dynamically created?

回眸只為那壹抹淺笑 提交于 2019-12-06 14:17:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!