1

I am working with loopback 2.0.

I generated my models with the yeoman generator and added a js file for each model to extend its behavior.

How can I call a method from ModelA within ModelB?

EXAMPLE

Folder structure:

/common
  /models
    Car.json
    Car.js
    Engine.json
    Engine.js
...

Car.js:

module.exports = function(Car) {
  Car.drive = function(destination, fn) { ... }
  ...
};

Engine.js:

module.exports = function(Engine) {
  Engine.doSomething = function(something, fn) { 
    // *** Here is where I want to invoke a method from the Car.js
    var loopback = require('loopback');
    var Car = loopback.models.Car;
    Car.drive('49.1234,12.1234', fn);
    // ***
  }
  ...
};
Craig Ringer
  • 307,061
  • 76
  • 688
  • 778
electronix384128
  • 6,625
  • 11
  • 45
  • 67

1 Answers1

6

The model class such as Engine will have a property app to provide access to other models, for example:

module.exports = function(Engine) {
  Engine.doSomething = function(something, fn) { 
    // *** Here is where I want to invoke a method from the Car.js
    var Car = Engine.app.models.Car;
    Car.drive('49.1234,12.1234', fn);
    // ***
  }
  ...
};
Raymond Feng
  • 1,516
  • 9
  • 5