views:

56

answers:

2

I want a generic error handler for my forms

var errorsBox = function() {
    var $errorBox = $('#form-error');

    return {
        add: function(errors) {
            if ($errorBox.length === 0) {
                $errorBox = $('<div id="form-error"><ul></ul></div>').appendTo('form');
            };

            $errorBox.find('ul > li').remove();

            $.each(errors, function(i, error) {
                $errorBox.find('ul').append('<li>' + error + '</li>');
            });
        }
    };
};

You can play with it on JSbin.

I'm getting

errorsBox.add is not a function

I'm sure it's really obvious, but I can't seem to understand why this might not be working.

What have I done wrong?

Thanks!

+6  A: 

You defined errorsBox to be a function. So, you'd call it likewise:

errorsBox().add(...)
casablanca
Wow, I feel like a kook. I'll accept as soon as I can!
alex
It happens to all of us at some time or the other I guess. :)
casablanca
+2  A: 

errorsBox is a function that returns an object. That returned object has an add() function.

You could do:

errorsBox().add(['error1', 'error2']);

but it looks a bit strange. Maybe you're not setting it up quite the way you want.

If you want to be able to call it the way you have it (errorsBox.add(...)), then try this:

var errorsBox = {
       $errorBox: ('#form-error'),

        add: function(errors) {

            if ($errorBox.length === 0) {
                $errorBox = $('<div id="form-error"><ul></ul></div>').appendTo('form');
            };

            $errorBox.find('ul > li').remove();

            $.each(errors, function(i, error) {

                $errorBox.find('ul').append('<li>' + error + '</li>');

            });
        }
};
Samuel Meacham
+1 thanks for this detailed answer.
alex
BTW, If I was going to use an object literal, I'd need to use `this.$errorBox` to access that variable wouldn't I?
alex
Yes, you would.
casablanca