electronix384128
electronix384128

Reputation: 6733

How to Call Method of ModelB.js from within ModelA.js?

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);
    // ***
  }
  ...
};

Upvotes: 1

Views: 158

Answers (1)

Raymond Feng
Raymond Feng

Reputation: 1536

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);
    // ***
  }
  ...
};

Upvotes: 6

Related Questions