samedi 25 avril 2015

Automated function reinitiating within jQuery plugin


I'm working on a drag an drop system wherein one can drag sliders from a panel to the page. On drop, I need to reinitiate the function that belongs to that particular slider so events can attach to handlers again. I could solve this by doing (assuming all functions that need to reinitiated are wrapped in a function named reInitSliders):

drop: function() {
  reInitSliders();
}

The problem with this is that it could go up to as much as 50 sliders (don't ask me why). I don't want the overhead of calling 50(!) functions on drop, so I've created a way to call the function that belongs to that particular slider. I've come as far as passing the current slider function name to the drop function,

drop: function(ui, event) {
  var slider = $(ui.draggable).attr('data-slider');
  $(slider).reInitObject();
}

and use that in my jQuery plugin to find the function that belongs to it by walking through a switch case.

$.fn.reInitObject = function() {

var targetFunction = this.selector;

 switch( targetFunction ) {
  case 'slider_wide':
    sliderWide();
    break;
  case 'slider_small':
    sliderSmall();
    break;
  default:
    return false;
 }

}

function sliderWide() {
  // Do stuff
}

function sliderSmall() {
  // Do stuff
}

So that's working. But I'm lazy and it just doesn't feel right to write out 50 conditions. Does anyone of you have a bright idea how I can loop/automate finding the right function in an efficient way?

Thanks!


Aucun commentaire:

Enregistrer un commentaire