1

I have a javascript function complaining that a call within its body is not a function before it is called. Could someone please help me explain this?

Context: I am using Meteor and Collection2 and I would like to use a function for reuse at different attributes of my Schemas. Precisely, I would like to do the following:

function foo (autoVal, self){
  if(something){
     return autoVal;
  }else{
     return self.unset();
  }
}

export const myCollection = new Mongo.Collection('myCollection');

const Schema = new SimpleSchema({
   my_field:{
      type:Boolean,
      autoValue: foo(false,this),
   }
});

myCollection.attachSchema(Schema);

When I save this and run Meteor, it does not launch and I get the following error message:

TypeError: self.unset is not a function

I feel that I am missing something about how javascript functions are called or executed, can someone point out why is this happening?

EugVal
  • 233
  • 1
  • 14
  • There is not enough there to reproduce whatever problem you are having. You should check out http://stackoverflow.com/help/how-to-ask and [MCVE] – pvg Dec 01 '16 at 05:51
  • figure out what `this` is when this code is executed `autoValue: foo(false,this);` - oh, and realise that foo is executed before `new SimpleSchema` is called (also that's not valid javascript, seems like the `;` at the end of `foo(false, this);` should not be there at all – Jaromanda X Dec 01 '16 at 05:52
  • `this` is not the `this` you're looking for. – godfrzero Dec 01 '16 at 05:53
  • It was a context issue with ```this``` indeed, thanks! – EugVal Dec 01 '16 at 05:58

1 Answers1

2

Try this:

function foo (autoVal, self){
  if(something){
     return autoVal;
  }else{
     return self.unset();
  }
}

export const myCollection = new Mongo.Collection('myCollection');

const Schema = new SimpleSchema({
   my_field:{
      type:Boolean,
      autoValue() {
        return foo(false, this);
      }
   }
});

myCollection.attachSchema(Schema);
kkkkkkk
  • 7,628
  • 2
  • 18
  • 31