简体   繁体   中英

how to use an object's properties to set another property with a callback function

I think this is different than the many other questions which are concerned with this and bind . Notably How to access the correct `this` context inside a callback?

I have a method on an object that uses that objects properties, and makes an ajax call. I want that value then stored in a new property object. I'm just not sure how to assign the callback function to the property.

Constructor:

function congressMember(state, district) {
  this.state = state
  this.district = district
}

Method on the prototype:

congressMember.prototype.getMember =
function() {
  govTrack.findRole({ current: true, state: this.state, district: this.district }, function(err, res) {
    if (!err) {
     return res.objects[0].person // this won't work
    }
  })
}

And then I want to make a new instance: var myHouseRep = new congressMember('WY', 1); The issue isn't with this but instead getting the value "out of" the callback.

Trying to keep the process transparent, here is a second stab:

function foo(state, district, fn) {
  govTrack.findRole({ current: true, state: state, district: district }, function(err, res) {
    if (!err) {
      fn(res.objects[0].person)
    } else {
      console.log('error')
    }
  })
}
congressMember.prototype.getDetails =
  function() {
    _this = this
    foo(this.state, this.district, function(cb) {
      _this.details = cb
    })
  }

You can define a variable as undefined, then assign a value.

var foo;

function bar(baz) {
  this.baz = baz;
  foo = this.baz;
}

bar(42)

console.log(foo) // 42

My second stab at the problem actually solves the issue, I was confused because I was console.og ing after the call to the method.

function foo(state, district, fn) {
  govTrack.findRole({ current: true, state: state, district: district }, function(err, res) {
    if (!err) {
      fn(res.objects[0].person)
    } else {
      console.log('error')
    }
  })
}
congressMember.prototype.getDetails =
  function() {
    _this = this
    foo(this.state, this.district, function(cb) {
      _this.details = cb
      console.log(_this) // The object now has the returned value
                         // as a property.
    })
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM