Backbone-relational
Backbone-relational copied to clipboard
reverseRelation does not work?
Week HasMany Days with reverseRelation
I want to get Week from any Day, but day.get('week') returns null
So the code is:
var Day = Backbone.RelationalModel.extend({
initialize: function(){
alert(this.get('week')); // Alerts null but should be 'first' week
}
});
var Week = Backbone.RelationalModel.extend({
relations: [{
type: Backbone.HasMany,
key: 'days',
relatedModel: Day,
reverseRelation: {
key: 'week',
}
}]
});
first = new Week;
first.get('days').create({name: "Monday"});
If reverseRelation is not meant to work like that, how can i get this functionality? PS: Here is the code http://jsfiddle.net/77rmbevw/1/
https://github.com/PaulUithol/Backbone-relational/issues/503
i would also really like to understand that, i have the same "issue"
That's because when initialize function is called, the model does not have relations yet. you could listen to change:week and call your function:
var Day = Backbone.RelationalModel.extend({
initialize: function() {
this.listenTo(this, 'change:week', function() {
alert(this.get('week'));
});
}
});
http://jsfiddle.net/77rmbevw/3/
I have a similar issue:
- Marionette composite view listening to an initially empty hasMany collection
- Call fetch on the collection to load some related models from server
- The models come, get added to the collection
- add triggered on collection, causing the view to be rendered.
- Inverse relation is then set on the new models
My problem is that my view depends on the inverse relation to pull a field from the parent model, so, #5 needs to happen before #4.
Current workaround plan is when I call fetch, stash the current parent model in some global state then get it out in an event attached to my new models being added to the collection.
TLDR: Everything should be in place before views render anything, currently not.