javascript - CoffeeScript - Should I have a callback? -


i'm working on simple coffeescript class learning purposes , i'm trying figure out if 'getmutant' method should have callback. code seems working is, in future i'd possibly query db or other timely asynchronous event. how write 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 method below have callback since i'm using result directly below?         opponentexists = mutant.getmutant(opponentname)          if opponentexists alert @name + " attacking " + opponentname else alert "no mutant name of '" + opponentname + "' found."      @getallmutants: () ->         @mutantarray      # possibly need add callback?     @getmutant: (name) ->         result = (mutant.name mutant in mutant.mutantarray when mutant.name name)         if result.length > 0 mutant else null  wolverine = new mutant("wolverine", 1, 2) rogue = new mutant("rogue", 5, 6)  rogue.attack("wolverine")  mutant.getallmutants() 

well question bit opinion based, might downvoted.

i'll take crack @ though. if have sort of backing store outside of code you'll have have asynch handlers in there -- anytime go network/io/database going asynch. don't think it's correct put getallmutants inside mutant class though. adapted of existing code getallmutants function 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 array")           else             onsuccess(mutants)             db.close()       ) 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -