views:

592

answers:

1

Thank you all ahead of time. This is my first time developing a jQuery plugin (and first time developing in javascript as well actually), and I have to say I'm pretty geeked (It probably has many hideous things to you seasoned js/jquery developers, but this is my first attempt - please bear with me :). I welcome any constructive criticism of any of the code too.

This is a model box plugin (yes, there are others, but job requirements dictate that I code my own to avoid third-party dependency) that displays text given, text from an ajax call, or a form given/taken from an ajax call and then handles the form submission via ajax. This needs to be as customizable as possible, so I am attemping to provide some hooks ( ?? - anonymous functions ) the user can use to pass custom code to the plugin.

The problem I am having is providing parameters to the user function. If I use the keyword 'this', I can pass the 'msg' variable fine and the user function can use it. But when I pass 'msg' instead of 'this' the user gets a blank variable. I would like to pass more than just the msg - also an array of data passed in the ajax call and a jQuery object of the model box is what I would really like to do.

Below is the snippet - the function is inside of and called within the plugin; I just grouped some code into functions for organization/development purposes.

 // Submits the form inside of the model box
 // and calls the user hooks of onFormSuccess and
 // onFormFailure for ajax success and error
 function submitForm() {
  var URL = $('form',$contentNode).attr('action'), 
  method = $('form',$contentNode).attr('method'),
  data = $('form',$contentNode).formSerialize();

  $.ajax({
   url: URL,
   type: method,
   data: data,
   success: function(msg) {
    // Doesn't work, but I would like it too
    //settings.onFormSuccess.call(msg, breakData(data) );
    // Does work
    settings.onFormSuccess.call(this);
   },
   error: function (XMLHttpRequest, textStatus, errorThrown) {
    setings.onFormFailure.call(errorThrown);
   }
  });
  closeModel();
 }
+2  A: 

See the call syntax. The first parameter determines what this will be inside the callback function itself. It is not passed as a parameter to the callback function.

To pass parameters to the callback you use the remaining parameters of call:

settings.onFormSuccess.call(thisArg, msg, dataArray);

The callback will then receive two parameters, and run with this pointing to thisArg:

function successHandler(msg, dataArray) {}

Another issue with your code is the value of this inside your success handler is meaningless. From what it looks like it will just point to the window object. So the callbacks you call will also be running with this == window.

Crescent Fresh