Peppered Lemons Peppered Lemons - 5 months ago 8
Javascript Question

jQuery Plugin: Add method with .each

I have the following code in a jQuery plugin:

$.fn.myForm = function() {
return this.each(function() {
var myForm = new MyForm(this);

$.data(myForm, 'myForm');
});
};


I thought that doing this, would allow me to then access the inner functions of myForm, such as getForm

var MyForm = function() {
//...
function getForm() {
return 'Hi';
}
}


But when I try to access 'myForm' from outside the plugin, I get undefined:

$('#test').myForm();
$('#test').data('myForm')
> undefined


What am I doing wrong here?

Answer

set your data like this:-

$(this).data('myForm', myForm);