Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone: how can I reference a Collection from a Model

Tags:

backbone.js

I know it's more often done in the opposite way, but in my specific use case I'd need to have a Model PostsTimes with a reference to a Collection (of another Model Post). Right now I'm trying:

var Posts = Backbone.Collection.extend({
    model: Post
});
var posts = new Posts(); // my collection



var PostsTimes = Backbone.Model.extend({
    url: "api/times.php",
    initialize: function(options){
        this.posts = options.posts;
    },
    test: function(){
        console.log(this.posts);
    }
});

var poststimes = new PostsTimes({posts: posts});

But this.posts in PostsTimes always stays undefined. Is there any way I can do this without defining a global variable?

like image 893
julien_c Avatar asked Aug 06 '12 15:08

julien_c


1 Answers

The structure of what you have is correct, so the reason it would be logging undefined is because the this in your test function is something other than the model's instance.

So your PostsTimes would become

var PostsTimes = Backbone.Model.extend({
    url: "api/times.php",
    initialize: function(options){
        _.bindAll(this);
        this.posts = options.posts;
    },
    test: function(){
        console.log(this.posts);
    }
});
like image 134
Bobby Avatar answered Sep 19 '22 15:09

Bobby