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.

0

1 Answer 1

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();

});
Sign up to request clarification or add additional context in comments.

5 Comments

Also $.proxy, though, bind is cleaner in this example, I think.
@Benjamin - nice timely edit; I was going to point out that you needed to use .on :)
@Tyblitz: .on() may be preferred, but it's not needed.
@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.
.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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.