0

I'm trying to use a JavaScript function with as an event handler for jQuery, but it needs one additional peice of information. I tried adding it on to an object with the data, and using this, but this is null when it gets executed. I believe this has something to do with function copying with in JavaScript. How can I pass my extra info.

<script type="text/javascript">
var WIDTH_ATTR = 'initWidth';

function resizeHandler(event, ui){
    var change = ui.size.width - this.master.attr(WIDTH_ATTR);
    this.slave.width(slave.attr(WIDTH_ATTR) - change);
};

function splitResize(master, slave, masterHandles){
    var s = new SharedResize(master, slave);
    master.resizable({ handles: masterHandles, resize: s.resizeHandler }); 
}

function SharedResize(master, slave){
    this.master = master;
    this.slave = slave;
    this.resizeHandler = resizeHandler;
    master.attr(WIDTH_ATTR, master.width());
    slave.attr(WIDTH_ATTR, slave.width());
}

// initialise plugins
$(function(){
    try {
        $('ul.sf-menu').superfish();
        splitResize($('#Content'), $('#InfoPanel'));
    }catch(ex){
        alert(ex.message);
    }
});
</script>

This code gives an error of

Line:13
'this.master' is null or not an object.

When a resize is attempted.

Can I make this scheme work, or is there another way to associate the event handler with my data.

0

2 Answers 2

1

Try this change:

function splitResize(master, slave, masterHandles){
    var s = new SharedResize(master, slave);
    master.resizable({ handles: masterHandles, 
        resize: function(event, ui) { s.resizeHandler(event, ui); } }); 
}

With that, the "resize" handler will be an anonymous function that, in turn, calls your handler with the proper context (the "SharedResize" instance).

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

3 Comments

thanks that works! I had to tweak your closure, but it got me close enough. I updated your answer to reflect my changes.
Oh ok good - I wasn't sure exactly what you meant by the "extra parameters" thing :-)
my original goal was to just pass in master and slave to the resize handler directly. I see how I could do that now, using a closure, but the object version is already written.
1

You can either do what Pointy suggested or you can do this:

function SharedResize(master, slave){
    this.master = master;
    this.slave = slave;
    this.resizeHandler = function(event, ui){
       var change = ui.size.width - this.master.attr(WIDTH_ATTR);
       this.slave.width(slave.attr(WIDTH_ATTR) - change);
    };
    master.attr(WIDTH_ATTR, master.width());
    slave.attr(WIDTH_ATTR, slave.width());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.