如何组织使用网络 api 时出现的大量 jquery & ajax 代码

how to organize the huge chunk of jquery & ajax code emerging when using web api

我正在使用 Web Api,并且每个实体都有一个控制器 class。但是,对于我的应用程序中的主页,我需要对大多数实体进行一些操作。我正在使用 jQuery & Ajax 来调用相关控制器 class。这已经创建了约 400 行代码,并且可能会增加到约 1000 行。例如,我需要编写一个 jquery 脚本来遍历返回的项目,并构建一个 table 以在我的页面中正确列出这些项目。

为了更好地组织它,我正在考虑将不同实体的 jquery 代码移动到单独的 *.js 文件中。我想知道是否有更好的方法来做到这一点。最好(但不是很复杂)的方法是什么?

更新 这是冗长的 jquery ajax 函数之一的示例:

    /////////////////////////////////////////////////////////
    //Functions -- Retriving posts and then displaying 
    function LoadPostsByDiscussionWall(currDiscussionWallId) {
        jQuery.support.cors = true;
        $.ajax({
            url: '/api/post/GetPostsByDiscussionWall?dwId=' + currDiscussionWallId,
            type: 'GET',
            contentType: "application/json; charset=utf-8;",
            dataType: 'json',
            success: function (response) {

                var posts = response["$values"];
                DisplayPosts(posts);

            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });
    }

    function DisplayPosts(posts) {
        if (posts.length) {

            $('#div_ListOfPosts').html('');
            $.each(posts, function (index, post) {
                var photo = ''; var displayname = 'Anonymous';
                if (post.IsAnonymous == true) {
                    if (post.Person.AnonymousPhoto.length)
                        photo = post.Person.AnonymousPhoto;
                    if (post.Person.AnonymousName.length)
                        displayname = post.Person.AnonymousName;
                } else {
                    if (post.Person.ProfilePhoto.length)
                        photo = post.Person.ProfilePhoto;
                    displayname = post.Person.FirstName + ' ' + post.Person.LastName;
                }

                var curruserid = $("#hdn_currUserId").val();
                var displayDeleteButton = "";
                if (curruserid === post.Person.Id)
                    var displayDeleteButton = '<a href="#" style="float:right;" data-postid=' + post.PostId + ' class="small text-muted">'
                          + '<span class="small glyphicon glyphicon-remove"></span></a>';

                var p = '<div>';

                p = p + '<img style="height:37px;float:left;" src=' + photo.replace('~', '') + ' />'
                      + '<div style="float:left;margin-left:5px;">'
                      + displayname
                      + "<br/><span class='small text-muted'>" + post.DatePosted + "</span>"
                      + '</div>'
                      + displayDeleteButton
                      + '</div>';

                p = p + '<div style="float:right;width:100%;margin-top:3px;"><a href="#" data-postid="'
                      + post.PostId
                      + '" class="text-primary postitem" style="font-family:arial;">'
                      + post.Title + "</a>";

                var postContent = post.Content;

                if (post.Content.length > 180) {
                    postContent = post.Content.substring(0, 180) + '...';
                }

                p = p + '<br/><p style="margin-top:3px;padding-bottom:7px;border-bottom:solid 1px #ebebeb;font-family:arial;" class="small">'
                      + postContent + "</p></div>";

                $('#div_ListOfPosts').append(p);

            });
        } else {
            $("#div_ListOfPosts").html("No posts were found. Select another discussion wall.");
        }

    }
    //END Functions -- Retriving posts and then displaying 
    ////////////////////////////////////////////////////////

代码的可重用性是关键。

为了您的特定目的,我会考虑创建自定义 jQuery plugin, or maybe even a jQuery UI - Custom Widget Factory

例如,在博客中,您可能希望 return 用户 posts 的许多不同位置 - 而不仅仅是他们的 homemain 页面.您可能希望 post 在站点的不同区域看起来不同。

您可以使用自定义 jQuery 插件函数来构建您的 post 实体,并接受 "settings/options" 作为参数。这样您就拥有了默认的 post 实体 "widget",但也可以更改外观而无需重新编写代码行。

这是一个使用 $.extend () 的示例代码段 - 但它与创建自定义插件的做法相距不远。

$(function() {

  var tar = $('#parent');

  tar.createPost(); // default "Post"

  // settings for a new post
  var settings = {
    "postWidth": "400px",
    "postContent": "Here's a new post!",
    "postBgColor": "yellow",
    "postData": "foo",
    "postTitle": "Oh no! Not another Post!",
    "postTitleBgColor": "pink"
  };

  tar.createPost(settings);

});



//---------------------------------------------------

// using extend() as an example
// you probably want to author your own plugin

$.fn.extend({

  // o = options
  createPost: function(o) {

    // d = defaults
    var d = {
      postContent: "No post content found! :(",
      postData: "na",
      postHeight: "100%",
      postWidth: "100%",
      postBgColor: "#d2d2d2",
      postTitleWidth: "100%",
      postTitleBgColor: "#fff",
      postTitleBorder: "solid 2px #ebebeb",
      postTitle: "NA",
      postTitleLink: "#",
      postContentFont: "Arial"
    };

    o = $.extend(d, o);

    // Set your function
    this.each(function() {

      // Post and post title elements

      var post = $('<div>');
      var postTitle = $('<a>');
      var postContent = $('<p>');

      // Build components

      post.attr("data-postid", o.postData);
      post.css({
        "height": o.postHeight,
        "width": o.postWidth,
        "background-color": o.postBgColor,
        "margin-top": "15px",
        "border": "dashed 2px lightblue"
      });

      postTitle.attr("href", o.postTitleLink);
      postTitle.text(o.postTitle);
      postTitle.css({
        "display": "inline-block",
        "background-color": o.postTitleBgColor,
        "border": o.postTitleBorder,
        "width": o.postTitleWidth
      });

      postContent.css({
        "font": o.postContentFont
      });

      postContent.html(o.postContent);

      post.append(postTitle);
      post.append(postContent);

      post.appendTo(this);

    });

    return this;

  }

});
.container {
  width: 800px;
  height: 500px;
  border: solid 1px #d2d2d2;
  margin-top: 25px;
  background-color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
  <div id="parent"></div>
</div>