如何创建骨干观点与动态创建一个'厄尔尼诺'? [英] How do you create Backbone views with an 'el' that was dynamically created?

查看:89
本文介绍了如何创建骨干观点与动态创建一个'厄尔尼诺'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个观点 - 一个OverlayView的和StoryView。的StoryView需要得到附加到OverlayView的(两者都是动态创建)。我动态创建#overlay格在OverlayView的,但是当我设置了StoryView的厄尔尼诺来#overlay,这一点。$ StoryView的EL是一个空数组。该#overlay DIV肯定在DOM通过创建StoryView时间存在。

我怎么识别创建#overlay作为它的厄尔尼诺的dyanmically的StoryView?我在假设'厄尔尼诺'应该是父容器视图所附加正确的?如果该OverlayView的的'厄尔尼诺'实际上是'#overlay?

OverlayView的:

  OverlayView的= Backbone.View.extend({
    EL:$('身体'),    事件:{
        点击#film':'hideOverlay
    },    初始化:功能(){
        this.render();
    },    渲染:功能(){
        这$ el.append('< D​​IV ID =叠加>< / DIV>');
        返回此;
    }
});

StoryView:

  VAR StoryView = Backbone.View.extend({
    EL:$('#覆盖),    事件:{
        点击.close':'closeStory
    },    初始化:功能(){
        this.render();
    },    渲染:功能(){
        的console.log($这个EL); //返回空数组[]
        返回此;
    }
});


解决方案

您的问题是,你的 StoryView 应该仅仅是一个选择 - 而不是一个jQuery对象。这将导致骨干为尝试检索在您指定的时间的对象(尚不存在)。只要改变 EL:$('#叠加')报:#overlay。你也可以做同样的 $('身体')你的第一个观点,因为它是没有必要的。只是始终使用选择,而不是jQuery对象和你会没事的。

工作例如这里

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;
    }
});

解决方案

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.

这篇关于如何创建骨干观点与动态创建一个'厄尔尼诺'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆