afkatja
afkatja

Reputation: 319

Method from imported class undefined

I'm trying to integrate a third party API into my meteor.js app. So the idea is, when on /blog route, the app should call external class' method.

router.js:

import blog from '../imports/scripts/blog';
FlowRouter('/blog', {
  name: 'blog',
  action: function(params) {
    blog.init(); // here I get the error "init is not a function" (it's undefined)
  }
});

blog.js:

export default class Blog {
  constructor(){
    ...
  }

  init() {
    console.log('init blog api');
    ...
  }
}

I'm using the latest meteor (1.4.2.3) and the following npm packages in order to enable ES2015:

"babel-cli": "^6.18.0",
"babel-core": "^6.18.2",
"babel-loader": "^6.2.8",
"babel-preset-es2015": "^6.18.0",
"babel-runtime": "^6.18.0",
"meteor-node-stubs": "^0.2.4",
"webpack": "^1.13.3"

Am I missing anything in my setup that I cannot call blog.init()?

Upvotes: 4

Views: 5271

Answers (3)

EduLopez
EduLopez

Reputation: 719

If you want to export a class you need to instantiate it afterwards, unless is a class with some static methods.

Let's assume this is a "helper" class with only static methods.

export class Logger {
    static info(message) {
        console.log(`Info: ${message}`);
    }

    static error(message) {
        console.log(`Error: ${message}`);
    }
}

export default Logger;

So you can import it and use it straight away.

import Logger from "../../../../utils/Logger";
...
Logger.Info("...");

Upvotes: 0

afkatja
afkatja

Reputation: 319

So this is answered by Yan Mayatskiy and Gothdo in their comments, thanks for that. In case anyone was looking for the correct answer:

I needed to instantiate the class I imported, like this:

import Blog from 'blog';
const blog = new Blog();
blog.init();

Upvotes: 4

user3752130
user3752130

Reputation: 41

I think you try import class(not class instance). Therefore you can't call methods.

change you blog.js something like:

class Blog {
  constructor(){
    ...
  }

  init() {
    console.log('init blog api');
    ...
  }
}
export default new Blog();

Upvotes: 3

Related Questions