user1679941
user1679941

Reputation:

Can I simplify this with a prototype function?

I am new to jQuery prototypes. I do this same code many times:

   $message
        .removeClass()
        .addClass("message error")
        .show()
        .html('<li>' + json.Errors.join('</li><li>') + '</li>');

the variables here are the "error" and the html data. For success the addClass would be "message success".

Is there a way I could combine these four into one function and then just call the one and pass it success/error and the data?

Upvotes: 1

Views: 80

Answers (2)

Pointy
Pointy

Reputation: 413915

Adding a jQuery function of your own is easy:

$.fn.showErrors = function() {
  return this.removeClass().addClass("message error").show()
    .html('<li>' + json.Errors.join('<li>'));
};

Then:

$message.showErrors();

Note that you don't really need the </li> closing tags.

In genera, a jQuery function added like that as a property of $.fn should expect this to refer to the current jQuery object. The function should return that value so that the normal chaining behavior of jQuery will work. The one slightly confusing thing is that because this is alread a jQuery object, there's no need to wrap it again — no need to write $(this) in other words.

edit — sorry I've been away from the Internet for a bit (shocking!) That code assumes that "json" is just floating around. It probably should be a parameter:

$.fn.showErrors = function(json) {
  return this.removeClass().addClass("message error").show()
    .html('<li>' + json.Errors.join('<li>'));
};

To call that:

$message.showErrors(json);

Upvotes: 4

Renato Zannon
Renato Zannon

Reputation: 29981

jQuery.fn.updateErrors = function(errors) {
  var cssClass, errorsHtml;

  if(errors.length === 0) {
    cssClass   = "success";
    errorsHtml = "";
  } else {
    cssClass = "error";
    errorsHtml = "<li>" + errors.join("</li><li>") + "</li>";
  }

  return this.removeClass().addClass("message " + cssClass)
             .show().html(errorsHtml);
};

It will decide if the class should be 'error' or 'success' depending on whether the errors array is empty or not. Of course, if you logic is more complex than that, this function could be the home for that as well.

Usage:

$message.updateErrors(json.Errors);

Upvotes: 0

Related Questions