I’m trying to teach myself some better JS development practice, so I’m writing my latest VLE widget in a JavaScript object wrapper.
var TutorGroupPoints = {
URL: 'http://staff.curriculum.local/frog/rewards.php',
CurrentUser: UWA.Environment.user.id,
Groups: { },
Sorted: [ ],
init: function() {
/* retrieve all of the groups from Frog and store them in a variable */
Frog.API.get('groups.getAll',
{
'onSuccess': function (data) { this.Groups = data; },
'onError': function(err) { alert(err); }
});
},
yearClick: function(year) {
alert( this.Groups );
for (var i = 0; i < this.Groups.length; i++) {
if (this.Groups[i].name.indexOf(year) == 0 && this.Groups[i].name.indexOf('/Tp') != -1) {
var arrayToPush = { 'id': this.Groups[i].id, 'name': this.Groups[i].name };
this.Sorted.push(arrayToPush);
}
}
}
};
widget.onLoad = function(){
TutorGroupPoints.init();
$('#nav li a').click(function() {
TutorGroupPoints.yearClick($(this).attr("id"));
});
}
The Frog.API call retrieves information about students/staff from our VLE (Virtual Learning Environment).
What I’m trying to do is store this information (retrieved in a variable called data) in a class-scope variable for use with other functions.
I thought I’d done that by declaring the Groups variable early on then using data = this.Groups, but then when I run the yearClick function, this.Groups simply appears as [object Object] where data alerts as loads of objects, i.e. [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object].
When I change Groups to [ ], the alert is entirely empty.
As such, I’m guessing that this is a scope problem. How can I store data from the Frog.API call in a variable which I can use with other functions? Previously I’ve just used functions, i.e. 'onSuccess': function (data) { someOtherFunction(data); }, but I don’t think that’s a very clean or practical way of doing it?
Thanks in advance,
This is a common mistake. Your success callback, being a function, changes the
thiscontext that code executes in. So in your callback,thisno longer points to theTutorGroupPointsobject.Either cache a reference to the outer
thisoutside the function…or bind a copy of it passed in via a closure, in this case an immediately-executing function