Skip to content

Instantly share code, notes, and snippets.

@zachlysobey
Last active October 16, 2015 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachlysobey/88e82ac1672d5f150c79 to your computer and use it in GitHub Desktop.
Save zachlysobey/88e82ac1672d5f150c79 to your computer and use it in GitHub Desktop.
Concept for angular "Vm" Injectable to replace `vm = this`

The standard approach

function MyController($scope, Vm) {
  const vm = this;
  vm.myData = 'foo';
  vm.myData; // 'foo'
  
  const stopWatching = $scope.$watch('controllerAsName.myData', (newVal, oldVal) => {
    doSomething(newVal, oldVal);
  });
  stopWatching();
  // no way to remove all watchers from controllerAsName.myData
}

My concept

function MyController($scope, Vm) {
  const vm = new Vm(this, 'controllerAsName');
  vm('myData').val('foo')
  vm('myData').val() // 'foo'
  
  const watcher = vm('myData').watch($scope, (newVal, oldVal) => {
    doSomething(newVal, oldVal);
  });
  vm('myData').stopWatching(watcher);
  vm('myData').stopWatching(); // unregister ALL watchers.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment