Skip to content

Instantly share code, notes, and snippets.

@ardeearam
Last active February 10, 2016 04:59
Show Gist options
  • Save ardeearam/0f7601ff5b56fd1701fe to your computer and use it in GitHub Desktop.
Save ardeearam/0f7601ff5b56fd1701fe to your computer and use it in GitHub Desktop.
An alternative to $scope.$watch
'use strict'
#Usage:
# efficientWatch.watch 'someProperty', ctrl, (newValue, oldValue) ->
# console.log("As good as $scope.$watch, without the digest tax!")
#Source: http://www.jomendez.com/2015/02/25/optimizing-code-object-defineproperty-scope-watch-angularjs/
#With my own changes:
# 1.) The attribute name is generic
# 2.) The callback function (3rd parameter) is passed with the oldValue as the second parameter, to mimic $scope.$watch better.
efficientWatch = () ->
watch = (name, controller, callback) ->
#Supported by IE9 and up. What the heck, IE is dead anyway.
Object.defineProperty controller, name,
get: () ->
attribute_name = "_" + name
return this[attribute_name]
set: (newValue) ->
attribute_name = "_" + name
oldValue = this[attribute_name]
this[attribute_name] = newValue
if typeof callback == 'function'
#mimic $scope.$watch
callback(newValue, oldValue)
service =
watch: watch
service
efficientWatch.$inject = []
angular
.module('appServices')
.factory 'efficientWatch', efficientWatch
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment