0

I have the following code:

 var FormCollection = function(collectionHolder, options) {

        // defines the collection holder object (the container where each element of the collection will
        // be added
        this.collectionHolder = collectionHolder;

        this.options = options;

        // count the current form inputs we have (e.g. 2), use that as the new
        // index when inserting a new item (e.g. 2)
        this.collectionHolder.data('index', this.collectionHolder.find(':input').length);

        this.addItem = collectionHolder.find('[data-collection-item-add]');
        this.addItem.on('click',function(e){
           e.preventDefault();

           // add a new tag form (see next code block)
           this.add();
        });          
  }

Now I want to define the add method called inside the click event, in the prototype because

FormCollection.prototype.add = function(){
    console.log(this.collectionHolder);     
  };

But it gives an error saying this.add is not a function. What is the best way to solve this?

brpaz
  • 3,618
  • 9
  • 48
  • 75
  • this inside this.addItem.on('click',function(e){}); refers to the clicked dom element and not the function. – Abhidev Feb 10 '14 at 13:02

1 Answers1

0

Inside the event handler function this will not refer to the instance (in your case it will refer to the clicked element). You can bind the event handler to the instance to execute it in the context of the instance:

this.addItem.on('click',function(e){
    e.preventDefault();

    // add a new tag form (see next code block)
    this.add();
}.bind(this));    

Or you can store a reference to this in the constructor and use that instead:

var _this = this;
this.addItem.on('click',function(e){
    e.preventDefault();

    // add a new tag form (see next code block)
    _this.add();
}); 
James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • I was so focus on the constructor function itself that I completely forgot some trivial thing like this context :( Thanks. – brpaz Feb 10 '14 at 14:24