Yeah, javascript is kind of funny that way. This is the main reason I use coffeescript. If you are accessing stuff on the this variable, you can just change the function from -> to => and preserve the this context. Makes it a lot simpler to deal with callbacks.
Another common thing to do is just say something like var that = this before the callbacks and use that instead of this inside. E On Jul 11, 2014 1:55 AM, "Charly Poly" <[email protected]> wrote: > You're welcome :) > > > On Friday, 11 July 2014 10:23:14 UTC+2, Liam Ryan wrote: >> >> Hi All, >> >> I'm trying to be clever and create prototypes to encapsulate a lot of my >> behaviour. I'm running into issues when I want a fulfilled promise to call >> another function in my prototype. >> >> Consider the following - >> >> function myClass ( ) { >> this.data = Object.create(this.data); >> this.$scope = Object.create(this.$scope); >> } >> >> myClass.prototype = { >> $scope: {}, >> data: {}, >> getData: function (url) { >> $http({...http stuff here...}) >> .then( function (httpData) { >> this.filterHTTPData( httpData ); >> }); >> }, >> filterHTTPData = function (data ) { >> console.log(data); >> } >> } >> >> >> The issue is that when the callback is executed (promise fulfilled) the >> "this" object will refer to window, not my instance of myClass. >> >> I've tried working around this as follows but it feels bad and will fail >> if there's any kind of delay ( I use callbacks in several places and nested >> promises, probably colliding with other tempobjects). >> Can anyone suggest a better way to handle this situation? >> >> myClass.prototype = { >> $scope: {}, >> data: {}, >> getData: function (url, $scope) { >> *$scope.tempObject = this;* >> $http({...http stuff here...}) >> .then( function (httpData) { >> *var thisObject = $scope.tempObject;* >> this.filterHTTPData( httpData ); >> *delete $scope.tempObject* >> }); >> }, >> filterHTTPData = function (data ) { >> console.log(data); >> } >> } >> > -- > You received this message because you are subscribed to the Google Groups > "AngularJS" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to [email protected]. > To post to this group, send email to [email protected]. > Visit this group at http://groups.google.com/group/angular. > For more options, visit https://groups.google.com/d/optout. > -- You received this message because you are subscribed to the Google Groups "AngularJS" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. Visit this group at http://groups.google.com/group/angular. For more options, visit https://groups.google.com/d/optout.
