Domanda

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
        });

})();
È stato utile?

Soluzione

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);
          });
}

Altri suggerimenti

One thing you can do is use the bind method of functions to set the context.

(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;
                }).bind(this),
                _error: (function (data) {
                    this._errorMessage = data.responseData;
                }).bind(this)

            },
            {

            }
        );

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

})();

I don't understand how those functions could get called in the wrong context though. Never mind, I see.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top