0

我是 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! 

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

我们做错了什么?

4

1 回答 1

1

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

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

这将创建window.BackofficeAppbut 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和朋友类属性:

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

这将创建BackofficeApp.Models, BackofficeApp.Collections, ... 这样你就可以说:

class BackofficeApp.Views.IndexView extends Backbone.View
  #...

TypeError没有看到

于 2012-12-10T06:15:45.577 回答