Skip to content Skip to sidebar Skip to footer

Sharing Meteor Functions Between Server, Client, And All Files Without Declaring Them Global?

Say that I've got functions that I want to re-use between multiple files on BOTH server and client. I could just make them global, place them into a common code folder, but that's

Solution 1:

If you want a piece of code not to be seen, you can't push it to the client. So you'll have put it in a method. That's the only meteor-native way. You can nicen up the Meteor.call api with something like this:

lib/

methodCaller = function methodCaller (methodName) {
  return function (/*arguments...[, callback]*/) {
    var callback = arguments.slice(-1)
    Meteor.apply(methodName, arguments, methodCallback)
  }
}

Meteor.methods({
  test: function (n) {
    return n*2
  }
})

test = methodCaller('test')

anywhere

test(1, function (err, result) {
  console.log(result)
})

If you are afraid of cluttering, just use a closure or as you proposed, a simple object. You don't have to define a local-scope variable to use a function stored in an object. You can just use it like this:

anywhere

globals.add()

Now I think globals is to generic a name. That just moves the cluttering problem to a different place. In your example you could for an example define a mathUtils object instead.

I don't use closures very often. There are some cases where it can bring a big benefit. once is a good example of this:

once = function (func) {
  var hasBeenTriggered = false
  return function (/*arguments*/) {
    if(hasBeenTriggered) return
    hasBeenTriggered = true
    return func.apply(null, arguments)
  }
}

This might not look like most closures, but it is one. Here hiding hasBeenTriggered is essential for the integrity of the function. Try not to hide unnecessarily. Having lots of hidden functions makes it harder to write good tests.


Post a Comment for "Sharing Meteor Functions Between Server, Client, And All Files Without Declaring Them Global?"