【问题标题】:Undefined property in ajax callback within controller property控制器属性中的 ajax 回调中的未定义属性
【发布时间】:2014-08-17 22:28:48
【问题描述】:

我在控制器上有一个登录功能,当我尝试在发布请求的“失败”回调中设置“消息类”和“消息”属性时,我无法弄清楚为什么它们出现未定义。如果我把它们放在回调之外,它们就很好了。我猜它与承诺有关,但我不知道为什么它无法访问上面定义的属性。非常感谢任何帮助。

App.UsersLoginController = Ember.ArrayController.extend
  message: ''
  messageClass: ''

  actions:
    login: ->
      email = @get 'email'
      password = @get 'password'

      url = "http://localhost:3000/api/v1/sessions/login"
      data = email: email, password: password

      request = $.post(url, data, (data)->
        console.log(data)
      ).fail((response)->
        @set 'messageClass', 'error'
        @set 'message', 'Wrong email or password'
      )

【问题讨论】:

  • 我完全认为“this”上下文在失败回调内部发生了变化,所以它不再指代控制器了。
  • @MatthewBlancarte 那是现象级的。我每天都在学习更多关于 coffeescript 的知识。

标签: ember.js coffeescript


【解决方案1】:

你可以使用粗箭头来解决这个问题。

(data) =>

对于非咖啡(我的偏好):

function (data) {
  this.doSomething(); // This function was cloned and returned with outer "this" context
}.bind(this)

或者:

var self = this;
function innerScope () {
  self.doSomething();  // outer "this" was cached as a variable.
}

希望有帮助!

【讨论】:

    【解决方案2】:

    我需要像上面提到的@MatthewBlancarte 那样从函数外部引用“this”:

      request = Em.$.post(url, data, (data)=>
        Em.run =>
          @set 'messageClass', 'success'
          @set 'message', 'All GOOD!'
      ).fail((response)=>
        Em.run =>
          @set 'messageClass', 'error'
          @set 'message', 'Wrong email or password'
      )
    

    双箭头使函数引用控制器的“this”。

    【讨论】:

    • 谢谢!很高兴我能帮上忙!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多