【问题标题】:Can't use constructor passed as function argument in CoffeeScript?不能在 CoffeeScript 中使用作为函数参数传递的构造函数?
【发布时间】:2012-06-28 10:02:03
【问题描述】:

编辑了更多上下文。当 $CONSTRUCTOR = pass_in 时,它会在 Firefox 和 Chrome 中抛出“passed_in is not a constructor”。当 $CONSTRUCTOR = not_passed_in 时,它不会

  initialize: (options) ->
    @collection.bind 'all', @render
    $('.search_box').parent('form').submit (event) => 
      @loading()
      event.preventDefault()
      query = $(event.target).find('.search_box').val()
      window.app.navigate('?query=' + query, trigger: true)
    passed_in = PaginationView
    @render(passed_in)

  render: (passed_in)=> 
    if @collection.isEmpty() && @collection.query
      @$el.html(JST['users/no_results'](query: @collection.query))
    else if @collection.isEmpty() # Not loaded yet
      @$el.html("<div class='loading'></div>")
    else
      html = JST['users/user_list'](@viewData())
      @$el.html(html)
      for user in @collection.models
        html = new UserListItemView(model: user).render().el
        @$('tbody.users').append(html)

      not_passed_in = PaginationView
      new $CONSTRUCTOR(
        type: "user"
        el: @$('.paginate')
        model: @collection
        data: {}
        onError: @onError
      ).bind('change', @loading)

这是 CoffeeScript 的已知(错误|功能)吗?还是我做错了什么?

(这些在 Backbone.coffee 视图中。我怀疑这是否相关)

【问题讨论】:

  • 我怀疑还有其他事情发生,因为我无法重现这一点。您能否发布更详细的代码示例?
  • 我也无法重现此类错误。我在我的一个 Backbone 应用程序中修改了一个视图,以便 intialize 将一个类类型传递给 render,然后它创建了一个所述类的实例,它工作正常
  • 您使用的是哪个版本的咖啡脚本编译器?适用于 1.3.3
  • 看编译好的javascript不是最简单的吗?

标签: backbone.js coffeescript


【解决方案1】:

为了简化问题:

MyView = Backbone.View.extend

    initialize: (options) ->
        passed_in = PaginationView
        @render(passed_in)

    render: (passed_in) => 
          not_passed_in = PaginationView
          new passed_in(
            type: "user"
            el: @$('.paginate')
            model: @collection
            data: {}
            onError: @onError
          ).bind('change', @loading)

1) 通常@render 的最后一行是@this 而不是另一个视图。

2) 最可能的问题是有一些其他代码在调用@render() 时不带任何参数。建议您提供一个默认参数,例如:

render: (passed_in=PaginationView) =>

3) 如果PaginationView 创建了MyView,你可能会得到一个堆栈溢出错误:

  • MyView.initialize 调用渲染,
  • 调用 PaginationView.initialize
  • 调用 MyView.initialize
  • .. 循环。

4) JSON.stringify 在任何时候都会被passed_in 调用吗?如果是,它会将函数转换为undefined

passed_in = JSON.stringify(passed_in)
undefined == passed_in
# always true if passed_in is a function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-02
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 2011-09-04
    相关资源
    最近更新 更多