【问题标题】:model.fetch success callback does not fire on firefox, but works on chromemodel.fetch 成功回调不会在 firefox 上触发,但适用于 chrome
【发布时间】:2011-08-11 02:16:20
【问题描述】:

我有一个模型获取的成功回调,并且在 chrome 上一切正常,但在 Firefox 上该事件不会触发。不过,根据控制台,请求已完成。

代码示例:

父类函数:

DownloadUserPromotions: (callback) ->
    self = @
    @model = new app.models.client({ id: JSON.parse($.cookie('jsondata')).id })

    lm = ->
      console.log "4"
      window.USER = self.model
      if typeof callback == 'function' then callback.call()   

    @model.fetch
      success: lm
      data: 
        relationships: 'client_promotions'
    console.log "3"

查看功能:

render: ->      
    self = @
    self.ReadUserInfo()
    console.log "1"
    renderTemplate = ->
      console.log "5"
      #Below Issue is wierd.......#TODO
      @USER = JSON.parse(JSON.stringify(@USER))
      $(self.el).html clientsPromotionsTemplate
        promos: USER.client_promotions
      $('.spinner#load').hide()
      self.FadeIn()

    $('.spinner#load').show()
    console.log "2"
    @DownloadUserPromotions renderTemplate  
    @

旁注:标记的 TODO 是一个不同的问题。额外感谢您帮助我弄清楚为什么 JSON 只能以这种复杂的方式工作。

【问题讨论】:

    标签: backbone.js coffeescript


    【解决方案1】:

    首先,您需要了解 => 和 -> 之间的区别,以便在 coffeescript 中定义函数。

    => 将函数内的 this 绑定到 this 在函数被定义时的状态。

    -> 将函数内部的 this 绑定到 this 函数被调用时的状态

    self = this  
    

    是咖啡脚本中的代码气味标志,当您尝试捕获 this 以解决 => 解决的问题时,您不了解如何正确使用上述内容。

    你可以重写渲染函数

    render: ->
        @ReadUserInfo()
        console.log "1"
        renderTemplate = =>
          console.log "5"
          #Below Issue is wierd.......#TODO
          @USER = JSON.parse(JSON.stringify(@USER))
          $(@.el).html clientsPromotionsTemplate
            promos: USER.client_promotions
          $('.spinner#load').hide()
          @.FadeIn()
    
        $('.spinner#load').show()
        console.log "2"
        @DownloadUserPromotions renderTemplate
        @
    

    并且可能会解决您的一些奇怪问题。以前我很确定 你的那条线

        @USER = JSON.parse(JSON.stringify(@USER))
    

    永远不会像您预期的那样工作,因为@USER 将扩展到 this.USER 和 调用回调时 this 可能是非常随机的,具体取决于 在您的框架和浏览器上。

    【讨论】:

    • 非常感谢您解释 => 与 ->。只是更改了很多代码以反映我的学习。绑定不是 USER 的问题。如果我不采取那种迂回的方式来获取对象,它仍然会引发错误。
    【解决方案2】:

    由于我的成功回调是 JSON 对象的一部分,firefox 找不到它正在寻找的任何默认值,因此没有触发任何东西。获取时指定 dataType:'json' 解决了这个问题,因为 firefox 知道在哪里寻找成功回调。

    Chrome 显然读懂了我的想法......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      • 2013-09-14
      • 2019-11-09
      • 1970-01-01
      相关资源
      最近更新 更多