简体   繁体   中英

Coffeescript - Method chaining with function arguments[2] or use functions instead of params

I start to learn CoffeeScript recently, and I faced with a problem as this. I want to write javascript :

TemplateManager.tmpl(this.template, this.modelJSON(), this.templateOptions()).done(
        function(rendered) { // something1
}).fail(function(ex) {
    // something2

});

Which way I can get it? I try rewrite that:

TemplateManager.tmpl @template, @modelJSON(), @templateOptions()
    .done (rendered) ->
       #something1
    .fail (ex) ->
       #something2

and I get:

TemplateManager.tmpl(this.template, this.modelJSON(), this.templateOptions().done(function(rendered) {

  }).fail(function(ex) {

  }));

Add parenthesis for tmpl and done methods

TemplateManager.tmpl( @template, @modelJSON(), @templateOptions() )
   .done( (rendered) -> 
        #something1 
    )
   .fail (ex) ->
        #something2

The solution isn't elegant, and I think others may give a better way in coffeescript

Updated

Base on comment, removing parenthesis for done . I've updated the code and I think this one is elegant

TemplateManager
   .tmpl(@template, @modelJSON(), @templateOptions())
   .done (rendered) -> 
        some
        code
        here 

   .fail (ex) ->
        another
        code
        here

Instead of making a mess of "I'm not using parentheses because they're optional" and tricky impenetrable indentation, just break things into little pieces, give the pieces names, and put them together simply:

done = (rendered) ->
    # something1
fail = (ex) ->
    # something2
TemplateManager.tmpl(@template, @modelJSON(), @templateOptions())
    .done(done)
    .fail(fail)

I have no idea what "something1" and "something2" are so I can't give them decent sensible names, consider done and fail as proof of concept names.

Just because a function can be anonymous doesn't mean is must be anonymous, just because some parentheses are optional doesn't mean that they must be left out.

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