javascript - Angular.js - Performance implications of binding a model to be watched, using $watchCollection -
i'm trying better understanding of new codebase, , haven't found ton of info (or maybe i'm not understanding have read) performance implications of choices made. previous maintainer isn't available insight.
each controller set make data request before being rendered using pattern:
$routeprovider.when('/path', { resolve: { somemethod: function($q) { var deferred = $q.defer(); .... stuff ... return deferred.promise; } });
this injected controller - part makes sense , understanding more performant because you're saving digests waiting data come through first. loading state shown default , removed when digest.
the value of injected param - in case somemethod
- assigned this.somemodel
.
throughout controller, remaining methods , properties set this.dostuff = function() { ... }
, this.property = 'some string'
, etc.
in end, watch setup , properties made available $scope
setting $watchcollection
this:
$scope.$watchcollection(angular.bind(this.somemodel, function() { return this; }), function(newtitle, oldtitle) { if (newtitle.title !== oldtitle.title) { self.updatethings(newtitle); } });
i understand it's binding context of watch current context of this
, watching changes on properties using $watchcollection
perform shallow reference checks of top level properties.
per this article using properties in templates {{ property }}
cause them watched, in case aren't watched until they're bound $watchcollection.
of course less expensive using $watch
, passing true
optional object equality param, better or worse performance perspective putting things directly onto $scope
? why, specifically?
i've never seen done way before, readings, insights, or things give me better understanding appreciated.
the real thing can think of author wanted keep off scope directly, populating properties of controller instance, available on scope via property specified in controlleras
property on route definition object.
however, when doing way, if want set $watch
es on scope notified of changes something, can't, because don't know property of scope published on.
you could settle on convention, such vm
, ctrl
or whatever, controlleras
value, not ideal , fragile , not concern of controller code itself. if made concession, use $scope.$watchcollection('vm.somemodel', ...
instead.
one final possible reason $scope.$watch()
, $scope.$watchcollection()
end dealing function thing use value of thing being watched during digest. if pass string, uses $parse
service under covers turn function. if pass function directly, no conversion necessary, can perceived minor performance improvement.
the real reason(s) may one, or none of these, valid reasons adopting approach. admire purity , strict adherence "controller as", in-vogue strategy encouraged angular team , community @ moment.