Pathsofdesign
Pathsofdesign

Reputation: 5038

CoffeeScript - Should I have a callback?

I'm working on this simple CoffeeScript class for learning purposes and I'm trying to figure out if my 'getMutant' method should have a callback. The code seems to be working as is, but in the future I'd like to possibly query a db or some other timely asynchronous event. How would I write a callback here?

Thanks!

class Mutant
    @MutantArray: []

    constructor: (@name, @strength = 1, @agility = 1) ->
        @name = @name.toLowerCase(@name)
        Mutant.MutantArray.push(@)

    attack: (opponentName) ->
        opponentName = opponentName.toLowerCase(opponentName)

        # Should the method below have a callback since I'm using the result directly below?
        opponentExists = Mutant.getMutant(opponentName)

        if opponentExists then alert @name + " is attacking " + opponentName else alert "No Mutant by the name of '" + opponentName + "' found."

    @getAllMutants: () ->
        @MutantArray

    # Possibly need to add callback?
    @getMutant: (name) ->
        result = (mutant.name for mutant in Mutant.MutantArray when mutant.name is name)
        if result.length > 0 then mutant else null

Wolverine = new Mutant("Wolverine", 1, 2)
Rogue = new Mutant("Rogue", 5, 6)

Rogue.attack("Wolverine")

Mutant.getAllMutants()

Upvotes: 0

Views: 53

Answers (1)

jcollum
jcollum

Reputation: 46569

Well this question is a bit opinion based, so it might get downvoted.

I'll take a crack at it though. If you have any sort of backing store outside of your code you'll have to have some asynch handlers in there -- anytime you go to the network/IO/database you are going asynch. I don't think it's really correct to put the getAllMutants inside your Mutant class though. I adapted some of my existing code to be a getAllMutants function from MongoDB.

getAllMutants: (onError, onSuccess) =>
  MongoClient.connect @config.dbUrl, (err, db) =>
    if err?
      onError("Failed: #{JSON.stringify err}")
    else
      collection = db.collection(@config.collection)
      collection.find().toArray( (err, mutants) ->
        if err?
          onError(err)
        else
          unless mutants?
            onError("No mutants object found")
          unless mutants.length?
            onError("No mutants object returned or not an array")
          else
            onSuccess(mutants)
            db.close()
      )

Upvotes: 1

Related Questions