2

I have a javascript module in javascript dojo toolkit. But I have a problem about using this keyword.

 define(["dojo/_base/declare","database/tool"],
        function (declare, databaseTool) {
            return declare(null, {
                person: null,
                spatialReference: null,

                constructor: function (parameters) {
                    this.person = parameters.person;                    
                },

                activatePerson: function () {

                    var db = new databaseTool();

                    var personOptions = {
                        "isActivated": true
                    };

                    var onActivated = function(result) {
                        var updatedPerson = result.person;
                        var oldPerson = this.person; //retuns <div id="person"/>
                    };

                    db.update(personOptions, onActivated );
                }
            });
        })

I want to use person object of module in onActivated method via this keyword. But this.person does not return javascript object. it returns <div id="person...>

barteloma
  • 5,342
  • 7
  • 55
  • 126
  • 1
    See this question (pun intended): http://stackoverflow.com/questions/3127429/javascript-this-keyword . Dojo has a `hitch` function for dealing with this: http://dojotoolkit.org/reference-guide/1.9/dojo/_base/lang.html#hitch – Frode Feb 13 '14 at 13:54

2 Answers2

2

Dojo has a function for that called hitch() (from the dojo/_base/lang module). Your solution would be:

var onActivated = function(result) {
    var updatedPerson = result.person;
    var oldPerson = this.person; //retuns <div id="person"/>
};

db.update(personOptions, lang.hitch(this, onActivated) );

It accepts two parameters, the first one being the object used as scope (this) and the second one begin the function.

g00glen00b
  • 34,293
  • 11
  • 80
  • 106
1
 var context = this;
 var onActivated = function(result) {
      var updatedPerson = result.person;
      var oldPerson = context.person;
 };

try that way.

Eugene P.
  • 2,635
  • 17
  • 23