Claudiu
Claudiu

Reputation: 4109

I'm getting an undefined model in backbone

I have this code:

    var Day        = Backbone.Model.extend({
        default: {
            service: 'None',
            concert: 'None',
            bible:   'None',
            social:  'None',
            play:    'None'
        }
    }),

    Day_view   = Backbone.View.extend({

        render: function(){
            this.$el.html('Service:' + this.model.service + '<br />Concert:' + this.model.concert + '<br />Bible:' + this.model.bible + '<br />Social:' + this.model.social + '<br />Play:' + this.model.play);
            return this;
        } 
    }),

    day_view = new Day_view({model: new Day({service: '10', concert: '11', bible:   '11', social:  '13', play:    '14' })});
    alert(day_view.render().$el.html());

And I get this:

Service:undefined Concert:undefined Bible:undefined Social:undefined Play:undefined

Where is the problem ? Thanks

Upvotes: 0

Views: 67

Answers (2)

ricardohdz
ricardohdz

Reputation: 579

Also, it is throwing that undefined error because you are not defining the el of the view. You have to pass a DOM element to the Backbone view as a hook point to insert the html.

$(document).ready(function() {
    var Day = Backbone.Model.extend({
        default: {
            service: 'None',
            concert: 'None',
            bible:   'None',
            social:  'None',
            play:    'None'
        }
    }),

    Day_view = Backbone.View.extend({
        el: 'body',
        render: function(){
            this.$el.html('Service:' + this.model.get('service') + '<br />Concert:' + this.model.get('concert') + '<br />Bible:' + this.model.get('bible') + '<br />Social:' + this.model.get('social') + '<br />Play:' + this.model.get('play'));
            return this;
        } 
    }),

    day_view = new Day_view({model: new Day({service: '10', concert: '11', bible:   '11', social:  '13', play:    '14' })});
    alert(day_view.render().$el);
});

Upvotes: 0

Ven
Ven

Reputation: 19039

The way you access attributes in Backbone is through get :

this.model.get('service')

Upvotes: 1

Related Questions