I want to create two JQuery functions. One of which will use the data created in the other function. Say:
jQuery.fn.myScroller = function (child) {
var $moveable = this.children(child);
var $children = this.children(child).children();
posl = posl.replace('px', '');
post = post.replace('px', '');
var varList = [];
$children.each(function () {
var currVar = {};
currVar.w = $(this).width();
varList.push(currVar);
});
// I want to save varList variable somehow.
this.varList = varList; // (1)
};
jQuery.fn.scrollUnitLeft = function () {
// Now I need to use this varList if this function called
// But the following returns undefined.
// However, I've saved it inside this at (1)
console.log(this.varList)
// More code...
}
$('#main_div').myScroller("#dummydiv");
$('#main_div').scrollUnitLeft();
As I explained in comments in the code, this doesn’t work.
How can I do this?
When you run your jQuery functions,
thisrefers to the jQuery object instance used in each case.In your code you create two jQuery object instances (one for every
$(...)call), so the data is set in the first instance, and hence not available to the second instance.If you were to run both your methods on the same jQuery object instance, they would work as expected.
To achieve what you intend, you have to persist the data someplace other than the jQuery object instance. jQuery offers a way to do this via the
.data()method. This method allows you to attach data to DOM elements. Check its documentation.You can test this snippets here: http://jsfiddle.net/HPjYn/
EDIT: I cannot yet comment on other people’s answers, but adding a jQuery prototype varable as suggested will make the data available from any jQuery object instance, which I don’t think is what it’s intended here.