0

I want to do an ember js find based on an id.

If an object with that id exists I would like to perform some logic on that object.

So, I do so based on the following code:

Cluey.UsersController = Ember.ArrayController.extend({
  keypadNum: "",
  loginWithPin: function() {
    var res;
    console.log("Login with pin: " + this.get('loginPin'));
    res = Cluey.User.find({
      pin: this.get('loginPin')
    });
    return res.on('didLoad', function() {
      var user;
      if (res.get('firstObject') != null) {
        user = res.objectAt(0);
        return this.doLogin(user);
      } else {
        return alert("User not found with pin " + this.get('loginPin'));
      }
    });
  },
  doLogin: function(user) {
    //some code
  }
});

The problem is that once I am in the res.on('didLoad') callback, I lose the scope of the controller, and therefore when I try to access this.get("loginPin"), it is returned as undefined.

Does anyone know how to solve this.

thanks!

4

2 回答 2

1

如果您将对象作为on事件中的第二个参数传递,它将成为回调中的上下文。

this您可以作为事件的第二个参数传递didLoad

res.on('didLoad', this, function() {
  var user;
  if (res.get('firstObject') != null) {
    user = res.objectAt(0);
    return this.doLogin(user);
  } else {
    return alert("User not found with pin " + this.get('loginPin'));
  }
});
于 2013-04-24T14:53:51.683 回答
0

您可以创建一个名为self并分配this给它的 var。

Cluey.UsersController = Ember.ArrayController.extend({
  keypadNum: "",
  var self = this;
  loginWithPin: function() {
    var res;
    console.log("Login with pin: " + this.get('loginPin'));
    res = Cluey.User.find({
      pin: self.get('loginPin')
    });
    return res.on('didLoad', function() {
      var user;
      if (res.get('firstObject') != null) {
        user = res.objectAt(0);
        return this.doLogin(user);
      } else {
        return alert("User not found with pin " + this.get('loginPin'));
      }
    });
  },
  doLogin: function(user) {
    //some code
  }
});
于 2016-11-03T20:43:37.957 回答