在Backbone.Marionette中为currentView对象返回undefined

时间:2012-12-10 21:54:38

标签: backbone.js coffeescript marionette

我正在测试布局如何监听其子视图的自定义事件。

我创建了一个jsFiddle here,其中我有一个布局,2个区域,我实例化了2个ItemViews并在布局的区域中显示它们。小提琴是在CoffeeScript中。

<div id="region"></div>
<script id="layout-tmpl" type="text/_">
    <h3>Heading</h3>
    <div id="content"></div>
    <div id="content2"></div>    
</script>

<script id="item-tmpl" type="text/_">
    <form>
        <label>Firstname:</lable>
        <input type="text" name="firstname" value="<%= firstname %>" />
        <input type="button" value="Save" id="save" />
    </form>    
</script>

CoffeeScript是:

SimpleLayout = Backbone.Marionette.Layout.extend 
    template: '#layout-tmpl' 
    regions:
        main: '#content'
        other: '#content2'
    initialize: () ->
        console.log @
    onShow: () ->
        _.each @.regionManagers, (region, name, something) =>
            console.log region.currentView
            # @.bindTo region.currentView, "custom:event", @callback           
    callback: () ->
        alert "HELL YEAH"

SimpleItemView = Backbone.Marionette.ItemView.extend
    template: "#item-tmpl"
    events:
        'click #save': 'save'
    save: (evt) ->             
        evt.preventDefault()
        @.trigger "custom:event"

region = new Backbone.Marionette.Region el: "#region"    
layout = new SimpleLayout() 
region.show layout
layout.main.show new SimpleItemView model: (new Backbone.Model firstname: "Olivier")
layout.other.show new SimpleItemView model: (new Backbone.Model firstname: "Travis")        

我希望布局能够收听ItemViews的自定义事件。在onShow中,我循环遍历区域管理器并尝试访问currentView对象,但它返回undefined。

如果我在SimpleLayout类之外附加相同的事件处理程序,并在显示项目视图后,则布局会正确处理自定义事件。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我认为正在发生的事情是,在调用布局onShow时,视图实际上还没有准备好:

layout = new SimpleLayout() 

region.show layout 

// onShow在这里调用,没有要绑定的视图,因为它们尚未创建

layout.main.show new SimpleItemView model: (new Backbone.Model firstname: "Olivier")
layout.other.show new SimpleItemView model: (new Backbone.Model firstname: "Travis") 

// now the views are ready, they can be bound to
_.each layout.regionManagers, (region, name) =>
    console.log region.currentView
    region.currentView.bindTo region.currentView, "custom:event", () ->
        alert "HELL YEAH"

Here's a forked Fiddle显示custom:event被触发。