开发者

jQuery Delete: Universal or Separate Functions?

My project has multiple lists, such as People, Jobs, Ranks. For each list, I have separate jQuery code, that looks something like this:

$('dl.person li.delete').live("click", function() {
  var personDL = $(this).close开发者_高级运维st('dl');

  if (confirm("Really delete person '" + personDL.find('dt').text() + "' ?")) {
    $.ajax({
      type: "POST",
      url: "/people/do-delete",
      data: "person=" + personDL.attr('id'),
      dataType: "json",
      timeout: 8000,
      success: function(data) {
        personDL.fadeOut("slow", function() {
          personDL.remove();
          var t = (data.total != 1) ? ' person' : ' persons';
          $('h3 span#people').text(data.total + t);
        });
      }
    });
  }

  return false;
});

As you can see, it would be pretty difficult to have one function to work for each list, as every instance of "person" needs to be replaced with "job", or "rank".

Should I try to get a single function (and is there an easy way to do that?) or should I keep things as they are?


If the HTML and URL structure is sufficiently similar across person/job/rank/etc., you could write a pretty simple generic function. Something like this:

function initDeletes() {

    var plurals = {
        person: 'people',
        job: 'jobs',
        rank: 'ranks'
    };

    $.each(['person', 'job', 'rank'], function (index, elt) {
        $('dl.' + elt + ' li.delete').live('click', function() {
            var $DL = $(this).closest('dl');
            var elts = plurals[elt];
            if (confirm("Really delete " + elt + " '" + $DL.find('dt').text() + "' ?")) {
                $.ajax({
                    type: 'POST',
                    url: '/' + elts + '/do-delete',
                    data: elt + '=' + $DL.attr('id'),
                    dataType: 'json',
                    timeout: 8000,
                    success: function(data) {
                        $DL.fadeOut('slow', function() {
                            $DL.remove();
                            var t = ' ' + (data.total === 1 ? elt : elts);

                            // no need for a more-specific selector
                            // adding anything beyond an ID is overspecifying
                            $('#' + elts).text(data.total + t);
                        });
                    }
                });
            }

            return false;
        });
    });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜