ruby-on-rails - Backbone + Coffeescript + Rails App Init 问题(2 级命名空间): Cannot read property 'IndexView' of undefined

标签 ruby-on-rails backbone.js namespaces coffeescript

我是 Backbone + Coffeescript + Rails 的新手,我一直在初始化应用程序。 main_app.js.coffee 是:

#= require_self
#= require_tree ./templates
#= require_tree ./models
#= require_tree ./views
#= require_tree ./routers

class window.BackofficeApp
  Models: {}
  Collections: {}
  Routers: {}
  Views: {}

  sanity:-> true

  constructor: ->
        console.log "go backofficeapp!"
        new BackofficeApp.Router()
        try
            Backbone.history.start()

路由器还是很简单的:
class BackofficeApp.Router extends Backbone.Router

    routes:
        "": "index",
        "users": "users",
        "csense": "csense"

    index: ->
        console.log "index called from router!"
        view = new BackofficeApp.Views.IndexView()
        $('#main-app').html(view.render().el)

    users: ->
        console.log "users"

    csense: ->
        console.log "contentsense!"

还有 IndexView:
class BackofficeApp.Views.IndexView extends Backbone.View    

    render: ->
        template = JST['index_view']
        $(@el).html(template);
        console.log "index called from indexview!"
        this

一切都从 jQuery 开始(文档就绪):
jQuery ->
    new BackofficeApp()

但是我们在控制台中看到以下消息/错误:
Uncaught TypeError: Cannot read property 'IndexView' of undefined
go backofficeapp!
index from router! 

如果我从 IndexView 类声明中取出 .Views,它会起作用……但是,由于应用程序是中到大型,我们希望在命名类时使用 2 个(或更多)级别。

我们做错了什么?

最佳答案

这不会像你认为的那样做:

class window.BackofficeApp
  Models: {}
  Collections: {}
  Routers: {}
  Views: {}

这将创建 window.BackofficeApp但是 Models , Collections , ... 将附加到 BackofficeApp.prototype而不是 BackofficeApp本身。 JavaScript 版本是这样的:
window.BackofficeApp = (function() {
  function BackofficeApp() {}
  BackofficeApp.prototype.Models = {};
  BackofficeApp.prototype.Collections = {};
  BackofficeApp.prototype.Routers = {};
  BackofficeApp.prototype.Views = {};
  return BackofficeApp;
})();

我想你想做 Models和 friend 类属性:
class window.BackofficeApp
  @Models: {}
  @Collections: {}
  @Routers: {}
  @Views: {}

这将创建 BackofficeApp.Models , BackofficeApp.Collections , ... 这样你就可以说:
class BackofficeApp.Views.IndexView extends Backbone.View
  #...

没有看到TypeError s。

关于ruby-on-rails - Backbone + Coffeescript + Rails App Init 问题(2 级命名空间): Cannot read property 'IndexView' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13795626/

相关文章:

ruby-on-rails - 仅具有查询字符串或数字的 Rails 4 路由约束

ruby-on-rails - Google Calendar API v3 - 更新事件

javascript - Backbone.extend 函数究竟是如何工作的?

javascript - 主干验证不起作用

c++ - 如何将全局范围函数声明为命名空间类的 friend ?

linux - 是否有任何标准机制或约定来防止 Bash 环境变量名称冲突?

ruby-on-rails - 在 View / Controller 中显示路由

ruby-on-rails - 如何在 ruby​​/rails 中将多个参数传递给 Proc?

javascript - 从 Marionette 中的 emptyView 添加到收藏夹

namespaces - Teamcity + NUnit - 从 dll 中排除程序集