javascript code architecture question

前端 未结 2 1618
慢半拍i
慢半拍i 2021-02-11 09:04

I\'m about to make a web app which will have a pretty heavy client end. I\'m not sure about the way to organize my javascript code, but here is a basic idea :

//         


        
2条回答
  •  一生所求
    2021-02-11 10:07

    That is similar to the way I do my JavaScript projects. Here are some tricks I have used:

    • Create one file for each singleton object. In your code, store ajax, middle layer and ui interface in separate files
    • Create a global singleton object for the 3 layers usually in the project; GUI, Backend and App
    • Never use pure ajax from anywhere outside the Backend object. Store the URL to the serverside page in the Backend object and create one function that uses that URL to contact the server.
    • Have a JSON class on the server that can report errors and exceptions to the client. In the Backend object, check if the returned JSON object contains an error, and call the serverError function in the GUI class to present the error to the user (or developer).

    Here is an example of a Backend object:

    var Backend = {};
    Backend.url = "/ajax/myApp.php";
    Backend.postJSON = function(data, callback){
      var json = JSON.stringify(data);
      $.ajax({
        type: "POST",
        url: Backend.url,
        data: "json="+json,
        dataType: "json",
        success: function(response){
          if(response){
            if(response.task){
              return callback(response);
            }else if(response.error){
              return Backend.error(response);
            }
          } 
          return Backend.error(response);
        },
        error: function(response){
          Backend.error({error:"network error", message:response.responseText});
        },
      });
    };
    Backend.error = function(error){
      if(error.message){
        Client.showError(error.message, error.file, error.line, error.trace);
      }
    };
    

    This can be improved by storing the ajax object somewher in the Backend object, but it's not necessary.

提交回复
热议问题