Skip to content

Instantly share code, notes, and snippets.

@jameswomack
Created August 28, 2012 02:49
Show Gist options
  • Save jameswomack/3494495 to your computer and use it in GitHub Desktop.
Save jameswomack/3494495 to your computer and use it in GitHub Desktop.
Technique for ensuring you have the info you need, and it's up to date
act: (context, f, keyPaths...) ->
ok = true
for k in keyPaths
if !context.get(k)?
ok = false
context.observe k, (newValue, oldValue, keyPath) =>
ok = true
for k in keyPaths
ok = context.get(k)?
return unless ok
f.apply(context) if ok
f.apply(context) if ok
setupCalendar: ->
@set '$', App.stateManager
@act @, @getCalendar, '$.user.grade', '$.user.program'
getCalendar: ->
_grade = App.stateManager.get('user.grade')
_program = App.stateManager.get('user.program')
console.log 'getCalendar', _grade, _program
App.CouchStorage.view 'calendar', {key: ["#{_grade}", "#{_program}", App.Calendar.unit(_program)]}, (err, results) ->
if err?
throw err
if !results?.length
alert 'Creating new calendar document'
App.calendar = new App.Calendar
setTimeout (=> App.calendar.save()), 1000
App.fire 'calendar_ready'
else
App.calendar = results.toArray()[0]
console.log 'Calendar pre-existed', App.calendar.get('id')
App.fire 'calendar_ready'
class Dude extends Batman.Object
act: (context, f, keyPaths...) ->
ok = true
for k in keyPaths
if !context.get(k)?
ok = false
context.observe k, (newValue, oldValue, keyPath) =>
ok = true
for k in keyPaths
ok = context.get(k)?
return unless ok
f.apply(context) if ok
f.apply(context) if ok
test: ->
@act @, @ready, 'crack', 'head'
setTimeout((=> @set('crack','$')), 500)
setTimeout((=> @set('head','$')), 1000)
setTimeout((=> @unset('crack')), 2000)
setTimeout((=> @set('head','¢')), 2500)
setTimeout((=> @set('crack','€')), 3250)
'testing...'
ready: ->
console.log @get('crack'), @get('head')
dude = new Dude()
dude.test()
### RESULTS:
testing... (0 sec)
$ $ (1 sec)
€ ¢ (3.25 sec)
###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment