将变量分配给Backbone.js中的窗口对象 [英] Assigning variables to the window object in Backbone.js

查看:67
本文介绍了将变量分配给Backbone.js中的窗口对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个很大的Backbone.js应用程序。代码使用 require.js 进行模块化结构化。
现在我看到很多骨干代码和教程都在这样做:

I am working on a big Backbone.js application. The code is modular structured using require.js. Now I see a lot of backbone code and tutorials doing this:

window.app = ( window.app || {} );

他们将模型定义和Collection实例分配给该全局对象后,如下所示:

after they will assign model definitions and Collection instances to that global object, like so:

Task = Backbone.Model.extend({ /*...*/ });
Tasks = Backbone.Collection.extend({ /*...*/ }); 

window.app.Task = Task;
window.app.Tasks = new Tasks();
// do this with all your models and collections

我喜欢这种方法,因为它简单并且不必处理何时何地实例化集合。但是,使用 require.js 首先将代码分成小块并且将所有内容一起分配给全局变量(除了全局变量通常是错误的代码风格)之前,似乎有些错误。 javascript)。

I like this approach for its simplicity and for not having to deal with where and when to instantiate a collection. But it somehow seems wrong to first separate the code into tiny bits using require.js and after assign all together to a global variable (apart from that global variables are generally bad codestyle in javascript).

那你对此有什么看法,这种方法的优点和缺点是什么?你如何处理Backbone中的对象?

So what is your take on this, what are the pros and cons of this approach and how do you deal with your objects in Backbone?

推荐答案

首先,污染全局名称空间并不是一个大问题,因为您可以将所有模型包装在自己的命名空间中:

First of all its not that big a problem to pollute your global name space as you can wrap all your model in your own namespace:

app = (app || {} );
app.Task = Backbone.Model.extend({ /*...*/ });
app.Tasks = Backbone.Collection.extend({ Model:app.Zask }); 

当涉及到requirejs时,它取决于项目的大小。我认为对于较小的项目,你可以不用。使用requirejs的好处不是防止命名空间污染,它的可维护性更好,因为你总能看到模块的依赖关系。您可以编写更好的单元测试,因为您可以测试模块并且模拟其所有依赖项。因此,我们从上述示例的结构重建了一个大型Backbone应用程序,如下所示:

When it comes to requirejs it depends on the size of your project. I think for smaller projects you can go without. The benefit of using requirejs isn't the preventing of namespace pollution, its the better maintainability because you always see the dependencies of a module. You can write better unit tests, because you can test a module and mock out all its dependencies. So we rebuild a large Backbone app from a structure like the above example into something like this:

models / Task.js

define(function () {
  return Backbone.Model.extend({ /*...*/ });
});

collections / Tasks.js

define([models/Task], function (Task) {
  return Backbone.Collection.extend({ Model:app.Task }); 
});

app.js

define([collections/Tasks], function (Tasks) {
  var tasks = new Tasks();
  tasks.fetch();
});

这篇关于将变量分配给Backbone.js中的窗口对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆