Skip to content

Instantly share code, notes, and snippets.

@mohuk
Last active August 29, 2015 14:25
Show Gist options
  • Save mohuk/bbdf2775a8aad70ddb35 to your computer and use it in GitHub Desktop.
Save mohuk/bbdf2775a8aad70ddb35 to your computer and use it in GitHub Desktop.
Passing read-only values as function parameters and not relying on the scope/this/vm available on the closure
/**
It is always a better idea to pass the readable items as function parameters when defining functions
on the scope/this/vm. Although the change is very subtle but as the code base grows bigger, this helps
identifying whats being read and written when a function is handling multiple things. Also, when calling
the function from the view, putting in the parameters there an then keeps the code readable and identifiable.
e.g.
<ul>
<!-- Clearly identifiable that the user being passed in is being selected -->
<li ng-repeat="user in users" ng-click="vm.select(user)"></li>
</ul>
**/
angular.module('app', [])
.controller('appCtrl', function(){
var vm = this;
vm.state = false;
vm.toggle = toggle;
////////////////
/**
This function works and is perfectly fine but writing it this way reduces the reusability of
the function as the function is dependent on the environment i.e. the scope/this/vm available
through the closure. This is not a BAD thing in anyway but it is a less cleaner and less reusable
way to define a function on the scope/this/vm.
**/
function toggle(){
vm.toggle = !vm.toggle;
}
/**
The function below has a few advantages over the one defined above.
1) Its a lot cleaner and has a clearly defined API
2) You can create a get/set with a single function this way
3) Code is more readable as the readonly values are passed in via arguments
and writeables are accessed via the closure
**/
function switch(state){
vm.toggle = state
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment