ontk
ontk

Reputation: 942

undefined returned for currentView object in Backbone.Marionette

I am testing how a layout can listen to its subviews's custom events.

I created a jsFiddle here where I have a layout, 2 regions and I instantiated 2 ItemViews and showed them in the layout's regions. The fiddle is in 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>

And the CoffeeScript is:

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")        

I want the layout to listen to the ItemViews's custom events. In the onShow, I am looping through the region managers and trying to access the currentView object but it returns undefined.

If I attach the same event handlers outside of the SimpleLayout class and after I show the itemviews, then the layout handlers the custom events properly.

Thanks for your help.

Upvotes: 1

Views: 1468

Answers (1)

McGarnagle
McGarnagle

Reputation: 102753

I think what's happening is that the views aren't actually ready when the layout's onShow gets called:

layout = new SimpleLayout() 

region.show layout 

    // onShow called here, no views to bind to, since they haven't been created yet 

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 that shows the custom:event getting triggered.

Upvotes: 1

Related Questions