开发者

create anonymous function with optional argument in Coffeescript

I'm new to Coffeescript and I'm having trouble turning this Javascript:

Handlebars.registerHelper("debug", function(optionalValue) {
  console.log("Current Context");
  console.log("================开发者_运维知识库====");
  console.log(this);

  if (optionalValue) {
    console.log("Value");
    console.log("====================");
    console.log(optionalValue);
  }
});

Into working Coffeescript. The part that I'm hung up on is, I think, how to pass the "debug" argument to the registerHelper function, and also pass in an anonymous function that takes an optional argument.

This syntax:

Handlebars.registerHelper: "debug", -> (optionalValue)
  console.log("Current Context")
  console.log("====================")
  console.log(this)

  if optionalValue
    console.log("Value")
    console.log("====================")

Is not working for me.


You have the param and the -> reversed.
You also don't need the semi-colon since you are calling the registerHelper function.

Handlebars.registerHelper "debug", (optionalValue) -> 
 console.log("Current Context")
 console.log("====================")
 console.log(this)

 if optionalValue
  console.log("Value")
  console.log("====================")
  console.log(optionalValue)

Which compiles out from coffeescript to javascript as:

Handlebars.registerHelper("debug", function(optionalValue) {
  console.log("Current Context");
  console.log("====================");
  console.log(this);
  if (optionalValue) {
    console.log("Value");
    console.log("====================");
    return console.log(optionalValue);
  }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜