ES6 Classes spread in different files

Hello Guys!

I want to start using ES6 Classes inside my meteor projects, but I don’t know how to do simple things a knew before.
For example, i don’t know how to define methods that can only be run on the server, something like this:

class MyClass {
   constructor() { }
   if(Meteor.isClient) {
      clientOnlyMethod () {
      }
   }
   if(Meteor.isServer) {
      serverOnlyMethod () {
      }
   }
}

I know the previous code is not correct, but I would like to know how to do it :smiley:
Please help!

You could hold your base class in /lib and extend them once in /server and once in /client

But you can extend with the same name?

One thing to note is to conditionally do this, you’re going to have to send the code to both user and client, and then omit parts (this could be a security issue).

You could extend ‘classes’ but you would have something like PushServer extends PushBase. I guess that works but you’re still jumping between files.

Yeah but i want to reproduce something like extending a base prototype in the server with some functions and in the client with some others.
So I guess it’s not possible with ES6 Classes.

Yea you’ll prob. have to use the old prototype method. I’ve personally switched to using modules with functions instead of ‘classes’ or constructors… they just don’t work well enough for me (compared to Ruby/Java).

For example this is a pattern I use that works well with the upcoming 1.3 modules:

// MyModule

clientOnlyFunc() {
  ...
}
serverOnlyFunc() {
  ...
}

// define an API
if(Meteor.isClient) {
  MyModule = { clientOnlyFunc1, clientOnlyFunc2 }
} else if(Meteor.isServer) {
  MyModule = { serverOnlyFunc1, serverOnlyFunc2 }
}

Yes that makes sense. Thanks! :smiley:
We have to wait for 1.3 then.

1 Like

So the above example is using Meteor 1.2 or lower (global modules). The 1.3 version would be slightly different, the nice part is that it’s easy to refactor once it gets here :smile:

// MyModule

clientOnlyFunc() {
  ...
}
serverOnlyFunc() {
  ...
}

// define an API
if(Meteor.isClient) {
  export default { clientOnlyFunc1, clientOnlyFunc2 }
} else if(Meteor.isServer) {
  export default { serverOnlyFunc1, serverOnlyFunc2 }
}

and then you could also do this if it’s easier than defining exports at the bottom:

// MyModule

if (Meteor.isClient) {
  export clientOnlyFunc() {
    ...
  }
}

if (Meteor.isServer) {
  export serverOnlyFunc() {
    ...
  }
}

1 Like

Or, if you’re an OLOO fan:

let BaseLogger = { 
  log(message) {
    console.log(message);
  }
};

let ClientLogger = Object.create(BaseLogger);
ClientLogger.logWithExtraDetails = function (message) {
  this.log(message + ' with extra client stuff');
};

let ServerLogger = Object.create(BaseLogger);
ServerLogger.logWithExtraDetails = function (message) {
  this.log(message + ' with extra server stuff');
};

if (Meteor.isClient) {
  Logger = ClientLogger;
} else if (Meteor.isServer) {
  Logger = ServerLogger;
}