On Jan 12, 1:59 pm, "Dave Maharaj :: WidePixels.com"
<d...@widepixels.com> wrote:
> I have this function:
> [ ... ]
> So it works fine but I have this in 5 pages on the site and was wondering
> how can I turn this into a standard function and call it like:
>
> addRecord(form_id);

There are several ways to do this.  The simplest is as follows:

    function internalAddRecord() {
        var data = $('#add').serialize();
        $.ajax({
            // ...
        });
    }

    function addRecord(formId) {
        $('#' + formId).live('click', internalAddRecord);
    }

    addRecord('myForm');

This is straightforward.  But it has one issue in that it pollutes the
global namespace with the internalAddRecord function, which presumably
shouldn't be used anywhere else.  You could make the function
anonymous, like this:

    function addRecord(formId) {
        $('#' + formId).live('click', function() {
            var data = $('#add').serialize();
            $.ajax({
                // ...
            });
        });
    }

But if that's not to your taste but you don't want to pollute the
global scope, you will need to store that internal function in some
other scope.  One technique stores it inside your main function like
this:

    function addRecord(formId) {
        function internalAddRecord() {
            var data = $('#add').serialize();
            $.ajax({
                // ...
            });
        }

        $('#' + formId).live('click', internalAddRecord);
    }

    addRecord('myForm');

This works; you expose only the addRecord function.  But it is a
little wasteful of memory as it creates a new copy of the
internalAddRecord function for every call to addRecord.  Another
variation which is syntactically more complex, but which saves you
that overhead would store the internal function inside a closure, as
such:

    var addRecord = (function() {
        function internalAddRecord() {
            var data = $('#add').serialize();
            $.ajax({
                // ...
            });
        }
        return function(formId) {
            $('#' + formId).live('click', internalAddRecord);
        }
    })()

    addRecord('myForm');

An alternative method involves creating a jQuery plug-in for your
functionality, so that you could use it like this:

    $("#myForm").addRecord().hide().fadeIn('slow');

That would have some advantages, but is probably not worth the
effort.  If you're interested, Mike Alsup's tutorial is excellent:

    http://www.learningjquery.com/2007/10/a-plugin-development-pattern

None of these are tested, of course.

Good luck,

  -- Scott

Reply via email to