I would like to define variables within scope of paginate(). However, any variable defined with this (e.g. this.parentlist) is not available within the jQuery click method
var paginate = function(elt) {
//would like to define variables within scope of paginate()
//however, any variable defined with this (e.g. this.parentlist) is not available within the jQuery click method
this.parentlist = elt.find('ul');
var listitems = elt.find('li');
this.listcount = this.list.find('li').size();
var showitems = '3';
this.numberofpages = ~~((this.count / this.show) + 1);
this.parentlist.after('<ul class="links"></ul>');
for(i=1;i<=this.numberofpages;i++) {
$('.links').append('<li><a href="#'+i+'">'+i+'</a></li>')
};
//click a link
$('.links a').click(function() {
//this.parentlist is not available here
listitems.hide();
this.start = listitems.index() * showitems;
this.end = (this.start + 1) * showitems;
this.selected = listitems.slice(this.start,this.end).show().addClass('selected');
console.log(this.selected);
console.log(this.parentlist);
});
};
paginate($('.pages'));
You use the
varkeyword to declare a variable within the current scope.The
myvarvariable is available “within” the click handler anonymous function because they were both declared “within” the same scope (the paginate function).However, once you’re inside the anonymous function,
thisrefers to the calling object of that function and not the function that it was declared in. If you need access tothisas the “paginate” caller, then you can cache thethisvariable like others are saying:var that = this;<– this is declaring a local variable (like above) and setting its value tothis.So, in your example, you can change it like this: