2013-05-14 2 views
0

У меня есть этот JS файлJavascript Prototype повторное же метод

function APIAccess(){ 
    this.LoadScreen = function(){ 
     var loadScreen = $('#loadScreen'); 
     if(loadScreen.html() == undefined){ 
      loadScreen = '<div id="loadScreen" style="display: none;width: 100%; height: 100%; top: 0pt;left: 0pt;">' + 
          '<div id="loadScr" style="filter: alpha(opacity = 65); z-index: 9999;border: medium none; margin: 0pt; padding: 0pt; width: 100%; height: 100%; top: 0pt;left: 0pt; background-color: rgb(0, 0, 0); opacity: 0.2; cursor: wait; position: fixed;"></div>' + 
          '<div id="loader" style="z-index: 10000; position: fixed; padding: 0px; margin: 0px;width: 30%; top: 40%; left: 35%; text-align: center;cursor: wait; ">' + 
          '<img src="img/ajax-loader.gif" alt="loading" /></div></div>'; 
      $(document.body).append(loadScreen); 
     } 
    }; 

    this.APICall = function(url, params, method, callback){ 
     this.LoadScreen(); 
     var postData = null; 
     if(params != null){ 
      postData = JSON.stringify(params); 
     } 
     if(url.toLowerCase().indexOf("http") < 0){ 
      url = "http://" + url; 
     } 
     $('#loadScreen').show(function(){ 
      $.ajax({ 
       url: url, 
       async: true, 
       type: method, 
       data: postData, 
       success: function(data){ 
       $('#loadScreen').hide(); 
       callback(data); 
       }, 
       error:function(data){ 
        alert("failure"); 
        return false; 
       } 
      }); 
     }); 
    }; 
} 

function Domain(reqCallback){ 
    this.url = 'http://beta.test123.net/api/domain'; 
    this.params = null; 
    this.method = 'GET'; 
    this.callback = function(data){ 
     setCookie("domain", data); 
     if(typeof reqCallback != null){ 
      reqCallback(data); 
     } 
    }; 
    this.request = this.APICall(this.url, this.params, this.method, this.callback); 
} 
Domain.prototype = new APIAccess; 

function Login(usermail, pass, reqCallback){ 
    var domainUrl = getCookie("domain"); 
    if(domainUrl == null) 
     return false; 
    else 
     domainUrl += '/api/login'; 

    this.url = domainUrl; 
    this.params = {"email": usermail, "password": password}; 
    this.method = 'POST'; 
    this.callback = function(data){ 
     setCookie("login", data); 
     if(typeof reqCallback != null){ 
      reqCallback(data); 
     } 
    }; 
    this.request = this.APICall(this.url, this.params, this.method, this.callback); 
} 
Login.prototype = new APIAccess; 

Если вы видите метод this.request = this.APICall(this.url, this.params, this.method, this.callback); будет повторяться каждый раз. Хотелось бы, чтобы его можно было разместить в функции APIAccess. можете ли вы предложить, что можно сделать.

Я использую это в моем HTML, как это

$(document).ready(function(){ 
      var domain = new Domain(function(data){ 
       alert(data); 
      }); 
      domain.request; 
     }); 

ответ

1

Я не уверен, если это то, что вы просите, самая важная часть приведенного ниже кода , что я использовал объект. create() вместо прототипа объекта, чтобы «наследовать» из базового класса. Если вы хотите узнать почему? посетить https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create

надеюсь, что это помогает :)

//Base class 
var APIAccess = { 

    LoadScreen : function() { 
     var loadScreen = $('#loadScreen'); 
     if (loadScreen.html() == undefined) { 
      loadScreen = '<div id="loadScreen" style="display: none;width: 100%; height: 100%; top: 0pt;left: 0pt;">' + 
          '<div id="loadScr" style="filter: alpha(opacity = 65); z-index: 9999;border: medium none; margin: 0pt; padding: 0pt; width: 100%; height: 100%; top: 0pt;left: 0pt; background-color: rgb(0, 0, 0); opacity: 0.2; cursor: wait; position: fixed;"></div>' + 
          '<div id="loader" style="z-index: 10000; position: fixed; padding: 0px; margin: 0px;width: 30%; top: 40%; left: 35%; text-align: center;cursor: wait; ">' + 
          '<img src="img/ajax-loader.gif" alt="loading" /></div></div>'; 
      $(document.body).append(loadScreen); 
     } 
    }, 

    APICall : function (url, params, method, callback) { 
     this.LoadScreen(); 
     var postData = null; 
     if (params != null) { 
      postData = JSON.stringify(params); 
     } 
     if (url.toLowerCase().indexOf("http") < 0) { 
      url = "http://" + url; 
     } 
     $('#loadScreen').show(function() { 
      $.ajax({ 
       url: url, 
       async: true, 
       type: method, 
       data: postData, 
       success: function (data) { 
        $('#loadScreen').hide(); 
        callback(data); 
       }, 
       error: function (data) { 
        alert("failure"); 
        return false; 
       } 
      }); 
     }); 
    }, 

    //added to base class 
    url : null, 
    params : null, 
    method : null, 
    callback : null, 
    request : function(){ 
     //TODO validate url, params and method here 
     APICall(this.url, this.params, this.method, this.callback); 
    } 
} 


var Domain = function(reqCallback) { 
    var obj = Object.create(APIAccess); 
    //obj.prototype = APIAccess; 
    obj.url = 'http://beta.test123.net/api/domain'; 
    obj.params = null; 
    obj.method = 'GET'; 
    obj.callback = function (data) { 
     setCookie("domain", data); 
     if (typeof reqCallback != null) { 
      reqCallback(data); 
     } 
    }; 
    return obj; 
} 

var Login = function (usermail, password, reqCallback) { 
    var domainUrl = getCookie("domain"); 
    if (domainUrl == null){ 
     return false; 
    } 
    else{ 
     domainUrl += '/api/login'; 
    } 

    var obj = Object.create(APIAccess); 
    //obj.prototype = APIAccess; 
    obj.url = domainUrl; 
    obj.params = { "email": usermail, "password": password }; 
    obj.method = 'POST'; 
    obj.callback = function (data) { 
     setCookie("login", data); 
     if (typeof reqCallback != null) { 
      reqCallback(data); 
     } 
    } 
    return obj; 
} 


//Code below is just for testing 
function getCookie(str){ 
    return 'test'; 
} 

console.log(
    new Domain(function(data){alert(data);}), //domain 
    new Login(//loging 
     'user', 
     'passwd', 
     function(data){alert(data);} 
    ) 
) 
1

OweRReLoaDeD's answer правильно, но поставить его более сжато:

Вы не должны создать экземпляр базового класса только для наследования настройки.

Domain.prototype = new APIAccess; 

Должно быть

Domain.prototype = Object.create(APIAccess); 

Сказав это, что вы моделирования выглядит немного странно с наследованием, жаль, что я успел предложить другой способ.

+0

не помог этим путем – 1Mayur

+0

«Не помогло», не объяснив, в чем проблема, не очень помогает –