This might be a weird question. Anyway, I'm working on a jQuery plugin and this is a useful piece of code for this question, note that it's not all ;) :
Javascript:
(function($){
$.fn.newPlugin = function(){
var ranges = [], selectableRange = this;
function init(){
selectableRange.live('mousedown', function(){
selectableRange.live('mouseup', function(){
addRange(Math.random(), Math.random());
selectableRange.die('mouseup');
});
});
}
function addRange(a, b){
// console.log(ranges);
ranges.push({start: Math.min(a,b), end: Math.max(a,b)});
console.log(ranges);
}
return { init: init };
};
})(jQuery);
$(document).ready(function(){
var instance = $('#element').newPlugin();
instance.init();
});
HTML:
<div id="element" style="width:200px;height:200px;background:grey;"> </div>
What it does seems pretty useless; anyway, every time someone puts his mouse down and then up on an element, a new object is added to the back of ranges
. Unfortunately, in my console the ranges array contains only one object, no matter how many times is clicked on $('#element')
.
I tried to figure out what was going on and uncommented the line console.log(ranges);
before an object was pushed to the back of the ranges array. Then, surprisingly, it worked. The ranges array grew...
Can somebody tell me why this .push
only works when ranges
is used before?