开发者

javascript code architecture question

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 :

// the namespace for the application
var app = {}; 

// ajax middle layer
app.products = {
  add : function(){
    // send ajax request 
    // if response is successful
       // do some ui manipulation
       app.ui.products.add( json.data 开发者_如何学编程);
  },
  remove : function(){},
  ... 
};
app.categories = {
  add : function(){},
  ....
};

// the ui interface which will be called based on ajax responses
app.ui = {};
app.ui.products = {
  add : function( product_obj ){
     $('#products').append( "<div id='"+product_obj.id+"'>"+product_obj.title+"</div>" );
  }
};
app.ui.categories = {};

Anybody got similar experiences to tell me the pros and cons of this approach? What's your way of designing client side javascript code architecture? Thanks.

[update] : This web app, as you see from the above, deals with products CRUD, categories CRUD only in a ajax fashion. I'm only showing an snippet here, so you guys know what I'm trying to achieve and what my question is. Again, I'm asking for inputs for my approach to organize the code of this app.


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.


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.


For client-side ajax handling I have a URL object that contains all my urls and than I have an ajax object that handles the ajax. This is not a centric approach.In my case I have I have different urls handling different tasks. I also pass a callback function to be executed into the ajax object as well.

  var controller_wrapper = {
     controller: {
    domain: "MYDOMAIN.com",
    assets: "/assets",
    prefix: "",
    api: {
        domainer: "http://domai.nr/api/json/info",
        tk_check: "https://api.domainshare.tk/availability_check"
    },
    "perpage": "/listings/ajax",
    "save_image": "/members/saveImage",
    "update": "/members/update",
    "check_domain": "/registrar/domaincheck",
    "add_domain": "/registrar/domainadd",
    "delete_listing": "/members/deactivateProfile",
    "save_listing": "/members/saveProfile",
    "get_images": "/images/get",
    "delete_image": "/images/delete",
    "load_listing": "/members/getProfile",
    "load_listings": "/members/getListings",
    "loggedin": "/members/loggedin",
    "login": "/members/login",
    "add_listing": "/members/add",
    "remove": "/members/remove",
    "get": "/members/get",
    "add_comment": "/members/addComment",
    "load_status": "/api/loadStatus"
}
}

   var common = {
    pager: 1,
   page: 0,
    data: {
    saved: {},
    save: function (k, v) {
        this.saved[k] = v;
    }
},
ajax: {
    callback: '',
    type: 'POST',
    url: '',
    dataType: '',
    data: {},
    add: function (k, val) {
        this.data[k] = val;
    },
    clear: function () {
        this.data = {};
    },
    send: function () {
        var ret;
        $.ajax({
            type: this.type,
            url: this.url,
            data: this.data,
            dataType: this.dataType !== '' ? this.dataType : "json",
            success: function (msg) {
                if (common.ajax.callback !== '') {
                    ret = msg;
                    common.ajax.callback(ret);
                } else {
                    ret = msg;
                    return ret;
                }
                return;
            },
            error: function (response) {
                console.log(response);
                alert("Error");
            }
        })
    }
}
    var callback = function (results) {
    console.log(results
    }
    common.ajax.callback = callback;
    common.ajax.type = "jsonp";
    common.ajax.type = "POST";
    common.ajax.url = controller_wrapper.controller.perpage;
    common.ajax.add("offset", common.page);
    common.ajax.add("type", $("select[name='query[type]']").val());
    common.ajax.add("max", $("select[name='query[max]']").val());
    common.ajax.add("min", $("select[name='query[min]']").val());
    common.ajax.add("bedrooms", $("select[name='query[bedrooms]']").val());
    common.ajax.add("sort", $("select[name='query[sort]']").val());
    common.ajax.send();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜