Skip to content

Instantly share code, notes, and snippets.

@dgageot
Last active August 29, 2015 14:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgageot/534ccfb7523d864451ed to your computer and use it in GitHub Desktop.
Save dgageot/534ccfb7523d864451ed to your computer and use it in GitHub Desktop.
AngularJs from Scratch - In CoffeeScript
# Scope
#
class Scope
constructor: ->
@$$watchers = []
$watch: (watcherFn, listener, byValue = false) ->
@$$watchers.push
fn: watcherFn
listener: listener
byValue: byValue
old: undefined
$digest: ->
for i in [1..10]
return unless @$dirty_check()
throw 'Digest is not stable'
$dirty_check: ->
console.log 'dirty_check'
dirty = false
for watcher in @$$watchers
old = watcher.old
value = watcher.fn(this)
changed = if watcher.byValue then !_.isEqual(value, old) else (value != old)
if changed
watcher.listener(value, old, this)
watcher.old = if watcher.byValue then _.clone(value) else value
dirty = true
dirty
$apply: (fn) ->
try
fn()
catch e
console.log "Error caught in $apply: #{e}"
finally
@$digest()
# Directives
#
$$directives = {}
$directive = (name, value) ->
if (value)
$$directives[name] = value
else
$$directives[name]
$compile = (node, scope) ->
for element in node.children
$compile(element, scope)
for attr in node.attributes
directive = $directive(attr.name)
if directive
console.log 'Found directive ' + attr.name
directive(scope, node, node.attributes)
# Application
#
scope = new Scope
$directive 'ng-bind', (scope, element, attrs) ->
scope.$watch (scope) ->
scope[attrs['ng-bind'].value]
, (value) ->
element.innerHTML = value
$directive 'ng-model', (scope, element, attrs) ->
scope.$watch (scope) ->
scope[attrs['ng-model'].value]
, (value) ->
element.value = value
element.addEventListener 'keyup', ->
scope.$apply ->
scope[attrs['ng-model'].value] = element.value
$compile(document.body, scope)
scope.$apply ->
scope.session = 'Zengular'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment