Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

$timeout & this #4

Closed
Siyfion opened this issue Jul 30, 2014 · 5 comments
Closed

$timeout & this #4

Siyfion opened this issue Jul 30, 2014 · 5 comments

Comments

@Siyfion
Copy link

Siyfion commented Jul 30, 2014

Given your controller with a $timeout:

function MainCtrl ($timeout) {
  this.clock = 'loading...';
  this.someObject = {};
  this.doSomething = function () {

  };

  var tick = function () {
    var today = new Date();
    // 'this.clock' isn't accessible here 
    $timeout(tick, 1000);
  };

  // Call it the first time to kick it off
  $timeout(tick, 0);
}

Should I be assigning a local variable like:

var _this = this;

// Then use (in the tick function):
_this.clock = today;
@jillesme
Copy link

I'll just add my two cents here, because I had a similar question and Todd told me he uses

var vm = this;

Where vm stands for ViewModel, I think it's really nice.

Cheers

@toddmotto
Copy link
Owner

Indeed I use vm = this;, as the controller is really a ViewModel here.

@johnpapa
Copy link

👍 Another reason why I use capture variable. Nice point

@Siyfion
Copy link
Author

Siyfion commented Jul 31, 2014

Yeah, after finding this issue and doing a bit of digging, I stumbled across your styleguide @johnpapa and I've done it the same way you suggest in this case.

@toddmotto might be worth adding something to the docs in the $timeout bit to push people in the right direction?

@toddmotto
Copy link
Owner

This is more to do with JavaScript and the lexical scope rules this doesn't follow, rather than Angular itself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants