Javascript和jQuery:从事件回调中访问类成员变量

Javascript and jQuery: accessing class member variables from event callback

本文关键字:访问 成员 变量 回调 事件 jQuery Javascript      更新时间:2023-09-26

我正在编写一个Javascript SDK与web服务交互。我正在使用jQuery做我的AJAX调用。

当AJAX调用失败时,我已经为在.js文件顶部调用的ajaxError注册了一个事件处理程序。我的问题是,我不明白为什么,当它被调用时,我没有办法访问我的akaman . client的类成员变量。

我试着为Akamanda添加另一种方法。客户端作为.prototype。logError,它被jQuery Ajax处理程序调用,但即使这样,(this.logging)的测试也失败了。

如何从jQuery回调访问类成员变量?我有什么不明白的吗?在ajaxError回调中,akaman . client .logging是未定义的。

SDK的代码:

$(document).ajaxError(function(event, jqxhr, settings, exception) {
    // more robust error handling for different conditions
    if (Akamanda.Client.logging) {
        console.log('FAILED: ' + settings.type + ' ' + settings.url + ' => ' + exception);
    }
});
Akamanda.Client = function(options) {
    this.URL = options.URL || 'http://m-test.akamanda.com';
    this.baseURL = this.URL + '/api/' + Akamanda.API_VERSION;
    this.feedsURI = '/websyndication/feed/';
    // who is the client? (iphone/android/web)
    this.clientName = options.clientName;
    // For development: Logging and buildcurl IS ON, for production: OFF
    //this.logging = options.logging || true;
    this.logging = true;
    // called when a user is not authorised (Disabled)
    // this.logoutCallback = options.logoutCallback || null;
}
Akamanda.Client.prototype.getFeeds = function(callback){
    var feeds = [];
    $.getJSON(this.baseURL + this.feedsURI, function(data) {
        $.each(data, function(index, feed) {
            feeds[index] = {
                name: feed.name,
                title: feed.title,
                link: feed.link
            };
        })
        callback(feeds);
    });//.error(function(err) { (disabled at the moment in favour of ajaxError event)
       //     console.log('Error: ' + err.error);
       // });    
}

我的客户端代码(在另一个JS源文件):

var options = { logging: true };
myAPI = new Akamanda.Client(options);
var feeds = [];
var articles = [];
function getFeeds()
{
    myAPI.getFeeds(function(AkamandaFeeds) {
        feeds = AkamandaFeeds;
        showFeeds();
    });
}

据我所知,从你发布的代码中,你从未实例化过Akamanda.Client类型的对象。

var Client = new Akamanda.Client();

var Akamanda.Client = {};
Akamanda.Client.logging = ....

JSBin示例:http://jsbin.com/ajidig/1/edit

好的,这里有一个小例子(真实的代码,但非常简化):

//we wrap our code in a self invoking function so that we don't pollute the global    namespace, see http://stackoverflow.com/questions/6715805/self-invoking-functions-javascript for further details
(function(){
     //create your object that holds all your function, that are different ways to do this
     var Akamanda = {};
     //a private function 
     function ErrorHandler(clientObj) {
          this.clientObj = clientObj;
          //do whatever with clientObj
          this.log = function(){..}
     } 
      //private constructor for clientobj
     function Client(options){
         ..
     }

     Akamanda.Client = function(){
       var newClient = new Client({..});
       //setup
       Akamanda.ErrorLogging = new ErrorHandler(newClient);
       return newClient;
     }
     //bind our service to the window object to make it accesible
     window.Akamanda = Akamanda;
})()

//client
var myAPI = Akamanda.Client();
Akamanda.ErrorLogging.log();
我希望这些基本的例子对你有帮助。如果你需要了解更多关于Javascript模式的知识,我可以推荐John Resig的这本书http://jsninja.com/,他是jQuery的创造者。根据你想做的事情,也有很多框架,如http://backbonejs.org/,可以帮助你完成这类事情。