【问题标题】:Namespacing a Backbone app using require js使用 require js 命名 Backbone 应用程序
【发布时间】:2012-12-04 15:10:43
【问题描述】:

我正在尝试为我的主干应用程序创建一个命名空间,以便我可以在全球范围内进行调用。

通常,我会这样做:

var myNamespace = window.myNamespace || {};
myNamespace.SomeView = Backbone.View.extend(..);

不知道如何使用 require js 实现这一点

标签: javascript backbone.js namespaces requirejs js-amd


【解决方案1】:

您可以在 requiredefine 调用中执行相同的操作,window 仍然存在(如果您在浏览器中工作)。

// views/app.js
define(['router', 'views/main-view'], function (router, mainView) {
  var App = function () { /* main app module */ };
  // do your "global" export
  window.App = App;
  return App;
});

// views/header-view.js
define(['views/app', 'models/user'], function (App, User) {
  // your header view code here
  // note that you have access to `App` already in a closure
  // but you can still talk to it by doing
  globalAppReference = window.App;
  globalAppReference === App; // true
});

问题是你为什么需要它?理想情况下,您的所有模块都将使用 requireJS 定义,因此您无需通过全局对象引用它们。

【讨论】:

  • 我同意@gryzzly。全局变量(命名空间是一种委婉说法)是旧方法。 RequireJS 模块是新的方式。你不需要或想要两者。只需使用 requirejs 模块。
  • 谢谢大家!这真的很有帮助。
猜你喜欢
  • 2012-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2014-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多