jQuery reusable functions and global vars
I have a function which also set a few global variables. The function itself works fine but whenever I call the function a second time the global variables get changed obviously.
Here's my theoretica开发者_如何学Gol setup:
var dataurl;
var datafunction;
function GetData(_url, _function)
{
dataurl = _url;
datafunction = _function;
}
//Afterwards dataurl and datafunction will used by other functions.
Now I'm very new to jquery and I'm not sure on how to create this in a proper way so it can be reused more then 1 time. Could someone please help me in the right direction?
It is possible to create objects:
var myObject = function() {
// Local variable
this.data = '';
// Function to call
this.callMe = function() {
alert(this.data);
}
// Function to set data
this.setData = function(newData) {
this.data = newData;
}
}
var a = new myObject();
a.setData('Hello World!');
a.callMe();
Not sure how this relates to an element (jQuery plugin), but here is how you can structure your prototype:
var DataHelper = function(_url, _function){
this.dataurl = _url;
this.datafunction = _function;
};
DataHelper.prototype = {
GetData: function(){
// loads data from storage
// using this.dataurl, and this.datafunction
}
};
Usage:
var dataHelper = new DataHelper('/mysite/url/', function(){
// data function
});
dataHelper.GetData();
精彩评论