Reputation: 1491
I am writing a jQuery plugin and am running into a few problems with regard to variables. For example I have the following skeleton structure for my plugin, which is going to act on a textbox. In my init function I want to set a variable and bind a keypress event to my textbox. That keypress event needs to call another function, in which I need the variable. Is this possible?
(function($){
var methods = {
init : function(options){
return this.each(function(){
var $this = $(this);
var someVar = 'somevar';
$this.keypress(function(event){
//I want to call my customFunction
});
});
},
customFunction : function(){
//I am wanting to access 'someVar' here
};
$.fn.mynamespace = function(method){
//handle which method to call here
};
})(jQuery);
Many thanks in advance.
Upvotes: 1
Views: 235
Reputation: 303224
Declare myVar
in an outer scope, and the fact that functions in JavaScript may be closures will allow what you want to work:
(function($){
var someVar;
var methods = {
init : function(options){
return this.each(function(){
var $this = $(this);
someVar = 'somevar';
$this.keypress(function(event){
//I want to call my customFunction
});
});
},
customFunction : function(){
//You may access 'someVar' here
};
$.fn.mynamespace = function(method){
//handle which method to call here
};
})(jQuery);
Edit: However, if you want to store data specific to each HTML element, you should use the data()
method of jQuery objects, or jQuery.data()
for the element itself. For example:
(function($){
var someVar;
var methods = {
init : function(options){
return this.each(function(){
var $this = $(this);
$this.data('myCode.blargle','somevar');
$this.keypress(function(event){
//I want to call my customFunction
});
});
},
customFunction : function(){
var someVar = $(this).data('myCode.blargle');
// or $.data(this,'myCode.blargle');
};
$.fn.mynamespace = function(method){
//handle which method to call here
};
})(jQuery);
Upvotes: 1