      1 var comb = require("comb"),
      2         hitch = comb.hitch,
      3         Promise = comb.Promise,
      4         PromiseList = comb.PromiseList,
      5         ManyToOne = require("./manyToOne");
      6
      7 /**
      8  * @class Class to define a manyToOne association.
      9  *
     10  * </br>
     11  * <b>NOT to be instantiated directly</b>
     12  * Its just documented for reference.
     13  *
     14  * @name MayToOne
     15  * @augments ManyToOne
     16  *
     17  **/
     18 module.exports = exports = comb.define(ManyToOne, {
     19     instance : {
     20
     21         //override
     22         //@see _Association
     23         _fetchMethod : "one",
     24
     25         //override
     26         //@see _Association
     27         _setter : function(val, self) {
     28             var loadedKey = self.loadedKey, name = self.name;
     29             if (!(val instanceof self.model)) {
     30                 val = new self.model(val);
     31             }
     32             if (this.isNew) {
     33                 this["_" + name] = val;
     34                 this[loadedKey] = true;
     35             } else {
     36                 //set my foreign key
     37                 val[self.rightKey] = this[self.leftKey];
     38                 this["_" + name] = val;
     39                 this[loadedKey] = true;
     40             }
     41         },
     42
     43         //override
     44         //@see _Association
     45         _postSave : function(next, self) {
     46             if (self.filter && self.isEager()) {
     47                 this[self.name].then(hitch(this, next));
     48             } else {
     49                 var loadedKey = self.loadedKey, name = self.name;
     50                 if (this[loadedKey] && this["_" + name]) {
     51                     var val = this["_" + name];
     52                     val[self.rightKey] = this[self.leftKey];
     53                     val.save().then(hitch(this, next));
     54                 } else {
     55                     next();
     56                 }
     57             }
     58         },
     59
     60         //override
     61         //@see _Association
     62         _preRemove : function(next, self) {
     63             if (self.filter) next();
     64             var loadedKey = self.loadedKey, name = self.name;
     65             if (!this[loadedKey]) {
     66                 this[name].then(hitch(this, function(value) {
     67                     if (value) {
     68                         value.remove();
     69                     }
     70                     next();
     71                 }));
     72             } else {
     73                 var value = this[name];
     74                 value.remove();
     75                 next();
     76             }
     77
     78         }
     79     }
     80 });