javascript code architecture question

前端 未结 2 1619
慢半拍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:01

    When you build something non trivial, encapsulation is important to make things maintainable in long run. For example, JS UI is not just simple JS methods. A UI components consists of css, template, logic, localization, assets(images, etc).

    It is same for a product module, it may need its own settings, event bus, routing. It is important to do some basic architectural code in integrating your chosen set of libraries. This had been a challenge for me when I started large scale JS development. I compiled some best practices in to a reference architecture at http://boilerplatejs.org for someone to use the experience I gained.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题