0

Given I have model mA, collection cA, model mB and collection cB.

mA contains a member that is the collection cB. mB contains a member that is the model mA. Models of type A are parents of type B. When I create a parent I want all of the children. When I create a child/children I want that child's parent. This however creates a cycle. My problems are two fold. The first problem I have is that in mB I get an ‘Undefined is not a function’ on the line var modelA = new mA(); when creating a new collection cA. Removing their interdependency stops the error but doesn’t help me. My second problem is how can I know if mB is created from mA and if so do not create a new cA member.

define(['cB'],function(cB){
  var mA = Backbone.Model.extend({
    parse:function(res,opt){
      var colB = new cB(res.id);
      colB.fetch();
      res.children = colB;
      return res;
    }
  });
  return mA;
});

define(['mA'],function(mA){
  var mB = Backbone.Model.extend({
    parse:function(res,opt){
      var modelA = new mA();
      modelA.set({id:res.parent_id})
      modelA.fetch();
      res.parent = modelA;
      return res;
    }
  });
  return mB;
});
var colA = new cA();
  1. How can I define that each file needs the other without the ‘Undefined is not a function’ error?
  2. How can mB know if it was created from mA?
RogerSmith
  • 204
  • 4
  • 11
  • Possible duplicate of http://stackoverflow.com/questions/4881059/how-to-handle-circular-dependencies-with-requirejs-amd . Did you check that one? – Sharadh May 21 '14 at 06:37
  • I don't know what you need to achieve but you have to decouple your application more. Why you're doing a fetch inside a parse? – chchrist May 21 '14 at 08:35
  • @Sharadh I have not seen that one. It may hold a solution to my problem. – RogerSmith May 21 '14 at 16:23
  • @chchrist I've decided to implement the child models such that instead of containing a reference to the parent model they contain the relevant attributes from the parent. The attributes are added in the response from the server. This has removed the cycle from the dependencies and should remove all problems. – RogerSmith May 21 '14 at 16:25

0 Answers0