尝试在 Fancybox 回调中调用 CoffeeScript 方法时出现范围问题

Scoping issue when attempting to call CoffeeScript method inside Fancybox callback

我有以下名为 Course 的 CoffeeScript 模块。我有一小段代码想重复使用,我创建了一个名为 preSelectItemSize.

的方法

我想在调用 init 时以及在 afterShow Fancybox 回调中调用此方法。以下代码 有效 ,但它认为使用模块名称是不正确的,我应该使用 @ 对 "this" 的引用。

我做错了什么? (为简洁起见减少了代码片段)

$ = window.jQuery = require("jquery")
Course =

  init: ->

    $('.js-product-overlay').on 'click', (e) =>
      @viewProductClickHandler(e, MediaDetection)

    @preSelectItemSize()

  viewProductClickHandler: (e, mediaDetection) =>

    $('.js-product-overlay').fancybox({
      href: wishlist_overlay_href
      maxWidth: '775px'
      minHeight: '495px'
      autoCenter: '!isTouch'
      height: 'auto'
      scrolling: true
      fitToView: false
      autoSize: false
      padding: 0
      tpl:
        closeBtn: '<a class="fancybox-item modal__close fancybox-close" href="javascript:;">Close</a>'
      afterShow: ->
        $('.js-fancybox-close').on 'click', (e) ->
          e.preventDefault()
          $.fancybox.close()

        Course.preSelectItemSize()
    })

  preSelectItemSize: ->
    itemId = $('.modal__product-info').attr('data-item-id')
    $('#size-' + itemId).click()

module.exports = Course

我认为你真正的问题是你使用的是一个简单的对象字面量而不是 class 所以 => 的行为并不像你期望的那样,你就离开了按名称引用 Course

如果我们看一个简化的例子:

o =
  m: =>

我们可以通过查看生成的 JavaScript 来了解发生了什么:

var o;
o = {
  m: (function(_this) {
    return function() {};
  })(this)
};

因为我们只有一个简单的数据结构(即一个普通的旧对象文字),所以没有构造函数将 m 绑定到任何实例,它的行为就像你说的那样:

m = =>
o = m: m

所以 o(或 Course 在你的情况下)的任何函数属性只是恰好是函数的普通旧属性,它们不是真正的方法。

您可以删除所有 fat-arrows 并按名称引用 Course,或者您可以切换到 class,以便 CoffeeScript 有一个实例可以将内容绑定到:

class Course
  #...
module.exports = new Course

以下工作通过将 viewProductClickHandler 更改为细箭头并将 afterShow 回调更改为粗箭头:

Course =

  init: ->

    $('.js-product-overlay').on 'click', (e) =>
      @viewProductClickHandler(e, MediaDetection)

    @preSelectItemSize()

  viewProductClickHandler: (e, mediaDetection) ->

    $('.js-product-overlay').fancybox({
      href: wishlist_overlay_href
      maxWidth: '775px'
      minHeight: '495px'
      autoCenter: '!isTouch'
      height: 'auto'
      scrolling: true
      fitToView: false
      autoSize: false
      padding: 0
      tpl:
        closeBtn: '<a class="fancybox-item modal__close fancybox-close" href="javascript:;">Close</a>'
      afterShow: =>
        $('.js-fancybox-close').on 'click', (e) ->
          e.preventDefault()
          $.fancybox.close()

        @preSelectItemSize()
    })

  preSelectItemSize: ->
    alert "preSelectItemSize executed."
    itemId = $('.modal__product-info').attr('data-item-id')
    $("#size-#{itemId}").click()

Course.init()

有关工作代码的示例,请参阅 fiddle:https://jsfiddle.net/L5u31Lzr/1/