简体   繁体   中英

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?

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);
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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM