无法访问窗口/全局变量 - 似乎没有定义

时间:2014-07-10 14:34:45

标签: javascript ruby-on-rails backbone.js

目标

访问window.MyApp

问题

如果我console.log(window),则会出现MyApp个对象;如果我做console.log(window.MyApp),控制台会抛出我:

  

未捕获的ReferenceError:未定义MyApp

更进一步

我在Rails(v 4.0.1)上使用Ruby(v 2.1.2)与Backbone(v 1.1.2)和Asset Pipeline。我的环境如下:

/app/assets/javascripts/backbone/myapp.js

//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require underscore
//= require backbone
//= require_tree ./templates
//= require_tree ./models
//= require_tree ./views
//= require_tree ./routers

window.MyApp = {
  Models: {},
  Collections: {},
  Routers: {},
  Views: {}
};

/app/assets/javascripts/backbone/routers/my_router.js - 错误发生的地方 - ,有以下内容:

console.log(MyApp);

/app/views/layouts/application.html.erb中,我以这种方式调用/app/assets/javascripts/backbone/myapp.js

<!doctype html>
<html>
<head>
  <!-- lots of stuff here -->
  <%= javascript_include_tag 'backbone/myapp' %>
</head>
<body>
  <!-- lots of other stuffs here -->
</body>
</html>

1 个答案:

答案 0 :(得分:0)

我不确定它是否发生在全局对象上,但声明可能会被提升。如果您将声明MyApp声明移到需求之上或另一个文件上,并在其他主干项之前需要它,那么它应该修复它。