I’m trying to loop through an array “fSel.sI”, and based on the data inside, pass them as values (not reference) on to a number of function declarations. Right now the problem is that mydrag contains a reference, and as draggable gets called it uses the last array item data. Hence when start: drag: stop: is called, the values are not unique. Help?
makeDraggable : function() {
// create new draggable
for (var i = 0; i < fSel.sI.length; i++) {
mydrag = fSel.sI[i];
$("#" + mydrag).draggable({
cancel: [''],
distance: 5,
containment: "#fWorkspace",
handle: mydrag,
start: function() { dragRegister(mydrag)},
drag: function() { dragItems(mydrag)},
stop: function() { dragStop(mydrag)}
});
}
},
You should look into closures.
Try the following code:
Your problem is with the
start,drag, andstopfunctions. They don’t execute immediately; by the time they do,mydraghas been set to another value. By wrapping a self-executing function around the code block containing these functions, we create a closure, wheremydragdoesn’t change.Note: For performance reasons, when accessing properties of an object more than once, it’s best to create a variable that references (or holds) the property. In your
forloop, I’ve created two variableslandsIthat storefSel.sI.lengthandfSel.sI(respectively) so that JavaScript doesn’t have to look up thesIandlengthproperties every time around the loop.