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?
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With