Coffeescript: Optional arguments
Sometimes you need to define a function with unknowm number of arguments - that's called optional arguments. As a good example might be a FB's feed dialog, where you combine default values with system pre-defined arguments.
Let's imagine we work on a campaign where all FB share images are same as well as other things, but the name, description and link should change depending on what element you click.
How to do that in Coffeescript? Well, it's quite easy as all thing in Coffeescript ;) Here it is:
facebookShareDialog: ({name, link, picture, caption, description, message}, callback) -> name ?= Environment::fb.name link ?= "#{globalAppVariables.baseUrl}/detail/#{entrantId}" picture ?= 'default value' caption ?= 'default value' description ?= 'default value' message ?= 'default value' callback ?= -> FB.ui method: 'feed' name: name link: link picture: picture caption: caption description: description message: message (response) -> callback(response)
As you can see, we need to setup default values at the beginning in case if there's no argument. There are several options how to do this - some of them are highlited in the example (like global objects or just a string).
The call then looks like this:
facebookShareDialog name: 'Share this!' description: 'You should really share this.' link: $(this).attr 'href' , (response) -> console.log 'All is ok!' console.log response
One thing is important. The last parameter is a callback so you should handle it as a callback -> see the indentation.














