Highway: how can I refer to a collection from a model

I know that this is most often done the other way around, but in my particular case I should have Model PostsTimes with reference to the assembly (another Post model ). Now I am 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.postsin PostsTimesalways undefined. Is there a way to do this without defining a global variable?

+5
source share
2 answers

The structure of what you have is correct, so the reason for registering it undefinedis that there is something other than an instance of the model thisin your function test.

So your PostsTimeswill

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

All Articles