2

I've got something like the following:

MyShape = function() {

    var _container = {
        width: 100,
        height: 100
    }


    this.draw() { 
       //do stuff...
    }

    $('#slider-1').bind('change', function(event, ui) {

        _container.width = $('#slider-1').val();
        this.draw();

    });


};

I'm using the jquery slider to dynamically change the width of my shape, then I call .draw() to redraw the shape. I keep getting this error though:

Uncaught TypeError: Object # has no method 'draw'

I'm fairly sure it's because I need to pass the context "this" into the change function, but I can't seem to figure out how to do that.

user602525
  • 3,126
  • 4
  • 25
  • 40

1 Answers1

8

This is caused because JavaScript's this is dynamic.

You can use Function.prototype.bind like so:

$('#slider-1').on('change', function(event, ui) {

    _container.width = $('slider-1').val();
    this.draw();

}.bind(this) /* use the same this value */);

Or you can use a closure variable

var that = this;
$('#slider-1').on('change', function(event, ui) {

    _container.width = $('slider-1').val();
    that.draw();

});
Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • 1
    Also [`$.proxy`](http://api.jquery.com/jQuery.proxy/), though, `bind` is cleaner in this example, I think. – crush Jan 13 '14 at 17:51
  • 2
    @Benjamin - nice timely edit; I was going to point out that you needed to use `.on` :) – webketje Jan 13 '14 at 17:51
  • @Tyblitz: `.on()` may be preferred, but it's not needed. – cookie monster Jan 13 '14 at 17:56
  • @user602525: Be aware that the `Function.prototype.bind()` used in the first example isn't available in IE8 and lower, as well as some other older browsers. – cookie monster Jan 13 '14 at 17:57
  • `.bind` just aliases `on`. This is its full source code `function(types, data, fn) { return this.on(types, null, data, fn);}` . It's better to use `.on` since it's the newer interface. – Benjamin Gruenbaum Jan 13 '14 at 17:57