styler
styler

Reputation: 16481

How do I pass data created in instantiated view to the view template using Backbone?

I have instantiated a view and created a data object that I would like to use in the views template but I'm not overlay sure how I get the newly passed data in order to pass it in to the template, I've a feeling I'm doing this totally wrong

WelcomeView.js

this.heroVideoView = new HeroVideoView({
                el: this.$el.find('.js-video-hero'),
                data: {
                    heading: 'This is my heading',
                    videoId: '5ZD4a3qDNlk'
                }
            });
            this.heroVideoView.render();

HeroVideoView.js

render: function() {

            // Render template contents right in to the main container
            this.$el.html( this.template({
                data: this.data
            }) );

            return this;

        },

Template

<a href="/" class="hero-content js-view-video transition-toggle" data-video="{{{data.videoId}}}">
    <div class="wrap">
        <div class="heading-info">
            <h2>{{{data.heading}}}</h2>
            <button class="btn btn-icon heading-button">
                <svg viewBox="8 5.1 11 14" class="icon icon-play">
                    <use xlink:href="#icon-play"></use>
                </svg>
            </button>
        </div>
    </div>
</a>

Upvotes: 1

Views: 31

Answers (1)

gruntledcustomer
gruntledcustomer

Reputation: 253

Not everything passed in the options hash when you create your view is attached directly to the view itself. If you pass in a property called "model" instead of "data", things will work as you suspect, as Backbone will automatically attach this property to the view.

Before Backbone 1.1.0, you could access other properties (such as your one called "data") passed to the view's constructor as, for example, this.options.data. However, since Backbone 1.1.0 you will have to capture such a property in the initialize method:

initialize: function (options) {
    this.data = options.data;
}

...

render: function() {
    this.$el.html(this.template({
        data: this.data
    }));
    return this;
}

Upvotes: 1

Related Questions