views:

31

answers:

2

Short version: I'm extending a jQuery object function that is intended to take 0-3 arguments and pass them off as the second to fourth arguments into jQuery.animate. Except, I want to isolate the callback and put in another function call at the end of it.


I'm extending the jQuery library the ordinary way, through jQuery.fn.newfunction = .... It's a custom animation function, specifically one that expands an object so that its outerwidth including margins equals the inner width of its parent node.

jQuery.fn.expand_to_parent_container = function() {
  var args = Array.prototype.slice.call(arguments);

  return this.each(function(){
    var parent = $(this).parent();
    parent.inner_width = parent.innerWidth();

    var inner_outer_differential = $(this).outerWidth(true) - $(this).width();

    // store original width for reversion later
    $(this).data('original_width', $(this).width());

    args.unshift({ width: parent.inner_width - inner_outer_differential });

    $.fn.animate.apply($(this), args );
  });
}

Simple enough. I'm using the arguments local variable, "casting" it as an array, and unshifting the first argument, which will go in the properties slot of .animate (API here). The intention, therefore, is to allow .expand_to_parent_container to take the arguments duration, easing, callback, with the usual jQuery convention of making them optional in intuitive patterns (e.g., if only a function is passed, it becomes the callback). It appears as though jQuery.speed is responsible for figuring out this mess, but I'd rather not use it/tamper with it directly because it does not appear to be as public/deprecation-proof as the other jQuery functions, and because I'd rather just delegate the task to .animate.

Here's my reversion function.

jQuery.fn.contract_to_original_size = function() {
  var args = Array.prototype.slice.call(arguments);

  var callback_with_width_reset = function(){
    callback();
    $(this).width('auto');
  }

  args.unshift({ width: $(this).data('original_width') });

  if($(this).data('original_width')) {
    $.fn.animate.apply($(this), args );
  } else {
    $(this).width('auto');
  }
}

I make my desired behaviour clear in var callback_with_width_reset ... assignment, in that I'd like for the width property to be reset to auto, both to restore it closer to its original state and to recover from any craziness that might happen over the course of lots of animations. However, I don't know how to piece out the callback function from arguments or args.

A: 

My current solution, which I suppose I will go with unless something better comes up, is the following:

var arguments_length = arguments.length;
for(var i = 0; i < arguments_length; i++) {
  if(typeof arguments[i] == 'function') {
    var temp = arguments[i];
    arguments[i] = function(){
      temp();
      $(this).width('auto');
    }
  }
}

In a related huh moment, the return value of Array.prototype.slice.call(arguments); does not seem to work as anticipated. Originally, instead of iterating through arguments, I set that prototype call to assign to args and then iterate via for(arg in args). But there was plenty of unexpected behaviour. Nevermind that for now, I suppose.

This seems to work, but it has two downfalls that don't seem to be important but still feel wrong.

  1. It's relatively "dumb" in how it detects which one of the arguments is the callback function.
  2. My resetting of arguments[i] is crucially dependent on the function taking no arguments. Fortunately, the callback function in .animate indeed takes no arguments, so it's not a huge deal now, but I suspect a more flexible extension would be more intelligent about handling this.
Steven Xu
Part 2 of your problem is easily solved: `temp.apply(this, arguments)` instead of `temp()`
gnarf
+1  A: 

There are a few things I'd like to point out real quick:

  • If you call expand_to_parent_container on multiple objects at once, you keep unshifting {width: ...} objects into args and never shift them back off.
  • contract_to_original_size doesn't use this.each() nor does it return this, and it will suffer from the same problems with unshifting width objects over and over.
  • You can make sure your code only sets original-width if it isn't already set, stopping one of your problems here (starting an expand while expanded / whatever wont mess with it! )
  • You can use $.map() on your arguments array to detect and replace your callback function pretty easily, if you still feel you need to.

Here is the code adjusted a little:

jQuery.fn.expand_to_parent_container = function() {
  // instead of Array.prototype, we can grab slice from an empty array []
  var args = [].slice.call(arguments);

  return this.each(function(){
    var parent = $(this).parent();
    parent.inner_width = parent.innerWidth();

    var inner_outer_differential = $(this).outerWidth(true) - $(this).width();
    // store original width for reversion later
    if (!$(this).data('original_width'))
    {
      $(this).data('original_width', $(this).width());      
    }

    args.unshift({ width: parent.inner_width - inner_outer_differential });
    $.fn.animate.apply($(this), args );
    args.shift(); // push the width object back off in case we have multiples
  });
}

jQuery.fn.contract_to_original_size = function() {
  var args = Array.prototype.slice.call(arguments);
  var callback;

  var callback_with_width_reset = function(){
    if (callback) callback.apply(this,arguments);
    // do something else like:
    // $(this).width('auto');
    // you may want to $(this).data('original-width', null); here as well?
  }

  args = $.map(args, function(param) {
    // if the parameter is a function, replace it with our callback
    if ($.isFunction(param)) {
      // and save the original callback to be called.
      callback = param;
      return callback_with_width_reset;
    }
    // don't change the other params
    return param;
  });

  // we didn't find a callback already in the arguments
  if (!callback) { 
    args.push(callback_with_width_reset);
  }


  return this.each(function() {
    // rather than shift() the new value off after each loop
    // this is another technique you could use:

    // create another copy so we can mess with it and keep our template
    var localArgs = [].slice.call(args); 
    // also - storing $(this) is going to save a few function calls here:
    var $this = $(this);

    if($this.data('original_width')) {
      localArgs.unshift({ width: $this.data('original_width') });
      $.fn.animate.apply($this, localArgs );
    } else {
      $this.width('auto');
    }    
  });
}

Check it out in action on jsFiddle

gnarf
Lovely. Thanks for taking the time. This worked superbly, and I learned some very useful practices for negotiating variable scope from your excellent code. I ended up removing the shift-unshift approach because it felt less intuitive than the localArgs approach. I also added a checker so that `.animate` is not called if the current width already equals the target width.
Steven Xu