Search code examples
windows-8windows-runtimewinjs

Access object's fields from callback functions


I recently start learning developing metro apps using js and I faced problem updating _title and _errorMessage fields in callback functions _success and _error. When these functions are called this no more refer to MyClass object. So my question is how can update these two fields from callback functions.

(function () {

 var MyClass = WinJS.Class.define(
            function () {},

            {
                _title: "",
                _errorMessage: "",

                Authorize: function () {
                    WinJS.xhr({url:"http://example.com"})
                        .then(this._success,this._error);
                },
                _success: function(data){
                    this._title = data.responseData;
                },
                _error: function (data) {
                    this._errorMessage = data.responseData;
                }

            },
            {

            }
        );

    WinJS.Namespace.define("MynameSpace",
        {
            MyClass: MyClass
        });

})();

Solution

  • You can use a proxy variable as shown below

    Authorize: function () {
         var _this = this;
         WinJS.xhr({url:"http://example.com"}).
         then(function(data){
                  _this._success(data);
              }, function(data){
                  _this._error(data);
              });
    }