StarJedi
StarJedi

Reputation: 1520

Meteor - How to call an external class methods from other JS files?

I'm new to meteor. I've been trying to write my meteor code the "object-oriented way" so I created an object called Message for my Parser and called it's methods from my app.js.

I would like to instantiate the object and call the methods defined in my Message.JS from my app.js?

App structure

App
  |--app.html
  |--app.js
  |--app.css
  |--message.js
  |--.meteor

message.js

  var Message = {


    init: function( message ){

   /* Initialization function with some properties */

   }

  getHash: function() {
    return this.hash_table;
   }

  parseMessage: function(input) {

 /* Some Parsing logic */

  return(hash_table);
 }
 }

app.js

if (Meteor.isServer) {

 var msg = new Message.init(response);
 var hash =  msg.getHash();
 console.log(hash);

}

Upvotes: 1

Views: 872

Answers (2)

Sander van den Akker
Sander van den Akker

Reputation: 1554

Variables declared with var have a file scope in Meteor, and cannot be accessed from within other files. If you declare the variable without var, it will have a bigger scope and can be seen from within your app,

Message = {
    ...
}

If that doesn't work, you might have a problem with the load order. The code in message.js should be loaded before the code in app.js gets called. To make sure it is, put message.js in the /lib folder. Files in this folder are always loaded before everything else.

Upvotes: 2

Marius Darila
Marius Darila

Reputation: 873

Add message.js into a folder named lib so it gets loaded first when meteor starts see http://docs.meteor.com/#/full/examplefilestructure. Then just remove var from Message so it becomes global.

Upvotes: 0

Related Questions