0

I have built my own object:

Main.utilities.pool = function (pool) {
    var counter=0;
    var $form = $(pool);

    return {
        add_pool_field: function(){
            $form.find('#practice_type').change(function() {
                if($(this).find("option:selected").val()){
                    var time = new Date().getTime();
                    var regexp = new RegExp( $(this).find("option:selected").data('id'), 'g');
                    $("#items").append('<li class="colorize">' + '<h1>' + this.increment_counter() + '</h1>' + $(this).find("option:selected").data('fields').replace(regexp, time) + '</li>');
                }
            });
        },
        increment_counter: function(){
            return ++counter;
        },
        init: function() {
            this.add_pool_field();
        }
    }
}

I call it as such:

var $profile_pool = Main.utilities.pool($('#new_form')).init();

The problem is in the change event, this refers to a select field. However, I want to access the increment_counter function of the actual anynomous object that was returned from the pool function. When I try this.increment_counter(), it thinks this is the html select field, and so it blows up. How can I gain access to that object within the context of the function passed to change?

Donato
  • 2,509
  • 3
  • 24
  • 54

2 Answers2

1

Just save a reference to this in local scope of add_pool_field().

    add_pool_field: function(){
        var self = this;
        $form.find('#practice_type').change(function() {
            if($(this).find("option:selected").val()){
                var time = new Date().getTime();
                var regexp = new RegExp( $(this).find("option:selected").data('id'), 'g');
                $("#items").append('<li class="colorize">' + '<h1>' + self.increment_counter() + '</h1>' + $(this).find("option:selected").data('fields').replace(regexp, time) + '</li>');
            }
        });
    },
Tap
  • 4,862
  • 3
  • 19
  • 24
  • @Vohuman, that was a typo made in haste. – Tap Oct 29 '14 at 19:53
  • Yes, I should have figured this out myself. The anonymous function passed to change creates a closure. This keeps everything in the containing function in scope, and that includes local variables such as self. Hence, self now stores a reference to the object and thus can be used in the anonymous inner function. – Donato Oct 29 '14 at 20:56
0

You need to keep a reference to the this that you want, by declaring it as a variable by your other variables -

var t = this;

Then within the change function, use t where you want to have access to the object's this.

rosscj2533
  • 8,745
  • 7
  • 39
  • 55