Backbone-relational icon indicating copy to clipboard operation
Backbone-relational copied to clipboard

reverseRelation does not work?

Open USvER opened this issue 11 years ago • 4 comments

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/

USvER avatar Oct 01 '14 17:10 USvER

https://github.com/PaulUithol/Backbone-relational/issues/503

tjwebb avatar Nov 18 '14 08:11 tjwebb

i would also really like to understand that, i have the same "issue"

linus-amg avatar Nov 30 '14 20:11 linus-amg

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/

4d4178 avatar Dec 08 '14 17:12 4d4178

I have a similar issue:

  1. Marionette composite view listening to an initially empty hasMany collection
  2. Call fetch on the collection to load some related models from server
  3. The models come, get added to the collection
  4. add triggered on collection, causing the view to be rendered.
  5. 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.

RalphSleigh avatar Jan 28 '15 18:01 RalphSleigh