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 SharedResi开发者_如何学Goze(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.
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).
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());
}
精彩评论