0

I trying to invoke a public method of my jquery widget api from a form.submit but I'm having no success. Can anyone help me?

_cleanFormFields: function() {
  console.log("ok");
},

_addFormListener: function(map, marker) {
    var form = $(".add-form").clone().show();
    form.submit(function (event){
       event.preventDefault();
       _cleanFormFields();
    }
}           

Why this does not work?? The browser's console raises "Uncaught ReferenceError: _cleanFormFields is not defined" exception

1
  • doesn't plugin have callbacks you can access from options? Or events you can bind to? Commented Dec 17, 2012 at 1:36

1 Answer 1

1

_cleanFormFields is a property of some object, right? So you can't call it directly, you need to reference it via your object:

yourObject._cleanFormFields();

Or, depending on how _addFormListener() is invoked you might be able to use this. But you'd need to keep a reference of the this from _addFormListener() because within the .submit() callback this will be the form element in question:

_addFormListener: function(map, marker) {
    var form = $(".add-form").clone().show(),
        self = this;
    form.submit(function (event){
       event.preventDefault();
       self._cleanFormFields();
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

OW!! It worked like a charm! _cleanFormFields is a method from my widget. I thought that I could invoke it from any place of it. Thank you! Hey, could you post any good tutorial for helping me to learn more JQuery as widgets?
I don't have any widget tutorials to hand, but jquery.com has links to tutorials, and MDN is a pretty good JavaScript reference. Note that the issue you had here is nothing to do with jQuery, it is a general JavaScript thing. If you use a constructor function rather than an object literal you can set things up so that your widget's methods can call each other directly, but in my opinion that is beyond the scope of this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.