简体   繁体   中英

Using Meteor: strange behavior using helper functions in template helpers

I'm getting some strange behavior using Meteor.

I'm in a template helper defined in client/ . The function "percentCompleted" is a helper function defined in client/lib/helper.js. When I call "percentCompleted" in the return line, percentCompleted completes normally. However, whenever I call percentCompleted outside of the return line, the console logs an error that the function "percentCompleted" is undefined. Why would a helper function be defined or undefined depending on where in the template helper it is called??

This works:

Template.chapter.percentComplete = function(){
  if(_.isEmpty(this))
    return "";

  return percentCompleted(this)
}

This throws an error with "percentCompleted" undefined.

Template.chapter.percentComplete = function(){
  if(_.isEmpty(this))
    return "";

  var percentCompleted = percentCompleted(this)  

  return percentCompleted;
}

The problem is that you have a local variable called percentCompleted which shadows the function percentCompleted . Rename the variable to something else and it should work.

Note that local variable declarations in Javascript are hoisted to the top of the function, so it behaves as if you wrote:

Template.chapter.percentComplete = function(){
  var percentCompleted;
  if(_.isEmpty(this))
    return "";

  // Here we attempt to call the function in the percentCompleted
  // var, but that is undefined.
  percentCompleted = percentCompleted(this)  

  return percentCompleted;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM