Question

I'm using a code like the following

function Basket () {
  this.items = new Array();
}
Basket.prototype.addItem = function(item) {
  this.items.push(item);
  setTimeout(this.showItems, 1000);
};
Basket.prototype.showItems = function() {
  console.log('items in Basket: '+this.items.join(', '));
}

var b = new Basket()
b.addItem('bananas')
// -> Uncaught TypeError: Cannot call method 'join' of undefined

When calling the addItem method, the showItems method is called properly, but in the showItems method the variable "this" does not reference to the Basket object. Using the Prototype framework I could do something like

setTimeout(this.showItems.bind(this), 1000)

This would bind the variable "this" to the Basket object in the showItems method.

Question: How can I achieve that in jQuery? Is there a more elegant method (best practice) than wrapping the calling method like so:

// ...
  $this = this
  setTimeout(function() {$this.showItems($this)}, 1000)

Basket.prototype.showItems = function ($this) {
  console.log('items in Basket: '+$this.items.join(', '));
}

I would also be happy, if someone could post some useful keywords, how I could search for that sort of problems, as I'm sure, I'm not the only one asking this. But naturally it is very hard to search for "prototype" when you don't have the framework in mind, but the extension of objects (or how you call it).

thx

Was it helpful?

Solution

Fortunately, jQuery offers a $.proxy method which has the same functionality as the bind provided by Prototype.

There is a documentation page available at http://api.jquery.com/jQuery.proxy/.

Hope that helps, Dave

OTHER TIPS

why not simply add the methods to Basket?

function Basket () {
  var items = new Array();
  this.addItem = function(item) {
     items.push(item);
     setTimeout(this.showItems, 1000);
   };
   this.showItems = function() {
      console.log('items in Basket: '+ items.join(', '));
   };
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top