jhamm
jhamm

Reputation: 25032

Backbone model not allowing me to get data

I am very new to Backbone and am doing a simple tutorial. I keep running into an error that I dont understand. Here is my code.

(function($) {
    dataModel = new Backbone.Model.extend({
        data: [
        {text: "Google", href: "www.google.com"},
        {text: "Yahoo", href: "www.yahoo.com"},
        {text: "Youtube", href: "www.youtube.com"},
        ]
    });

var View = Backbone.View.extend({
    initialize: function(){
        this.template = $('#list-template').children();
    },
    el: $('#container'),
    events: {
        "click button": "render"
    },
    render: function(){
        var data = this.model.get('data');
        for(var i = 0, l = data.length; i < l; i++){
            var li = this.template.clone().find('a').attr('href', data[i].href).text(data[i].text).end();
            this.el.find('ul').append(li);
        }
    }
});

var view = new View({ model: dataModel });
})(jQuery);

When I call this.model.get('data') I get the error TypeError: Object function (){return a.apply(this,arguments)} has no method 'get'. Please show me my error. Thanks.

Upvotes: 0

Views: 140

Answers (3)

Moszeed
Moszeed

Reputation: 1037

a model define`s only the structure of one data element

Model
    defaults:
       text : null
       href : null

what you need is a Collection

Collection
    model : Model

you can then set data to the collection with .add

Collection.add([
    {text: "Google", href: "www.google.com"},
    {text: "Yahoo", href: "www.yahoo.com"},
    {text: "Youtube", href: "www.youtube.com"},
])

to get the data from the collection look here http://underscorejs.org/#collections

Hope it helps

Upvotes: 0

codemonkey
codemonkey

Reputation: 5267

Your 'dataModel' is just the definition of the Model. You need to create a model instance by calling new dataModel() when you pass it to the view.

Upvotes: 0

Tom Tu
Tom Tu

Reputation: 9583

All the properties and methods you pass when extending a model are set on its prototype not as its attributes, and dataModel here is not a Backbone model instance but a Backbone Model subclass. If done this way to access the data property you'd need to instantiate the model and do a modelInstance.data rather then modelInstance.get('data') as if it would be when data would be set as model attribute as shown in the example below.

What you wanted to do here was

var dataModel = new Backbone.Model({ // without the extend!
    data: [
    {text: "Google", href: "www.google.com"},
    {text: "Yahoo", href: "www.yahoo.com"},
    {text: "Youtube", href: "www.youtube.com"},
    ]
});

as you want to create an instance of a model rather then subclass Backbone.Model class. Extend method is used to subclass core Backbone classes – views, models, collections and routers.

Upvotes: 2

Related Questions