简体   繁体   English

为什么在Backbone / Require.js项目中的每个JS文件中都包含jQuery和下划线

[英]Why include jQuery and underscore in every JS file in Backbone/Require.js project

In almost every Backbone/Require.js project you will see models and views that look similar to this: 在几乎每个Backbone / Require.js项目中,您都会看到与此类似的模型和视图:

define([
    'jquery',
    'underscore',
    'backbone'
], function ($, _, Backbone) {
    //Some code goes here, perhaps a Backbone model or view
});

But, assuming that you set up your Require.js shims correctly (with the Backbone shim including something like deps: ["underscore", "jquery"] ) you only need to define Backbone--defining Backbone as a dependency implicitly defines jQuery and Underscore as dependencies as well! 但是,假设您正确设置了Require.js填充程序(使用Backbone填充程序包括deps: ["underscore", "jquery"] ),您只需要定义Backbone - 定义Backbone作为依赖项隐式定义jQuery和下划线也是依赖项! Thus this would also be correct: 因此这也是正确的:

define([
    'backbone'
], function (Backbone) {
    //Some code goes here, perhaps a Backbone model or view
});

Personally, I would define jQuery or Underscore in a file that explicitly used their functions--but in something like a simple no-frills Backbone model file, they seem like cruft. 就个人而言,我会在一个明确使用其功能的文件中定义jQuery或Underscore - 但是在一个简单的简洁的Backbone模型文件中,它们看起来像是残酷的。

Why do I so frequently see the pattern of superfluous jQuery and Underscore definitions? 为什么我经常看到多余的jQuery和Underscore定义的模式? Why has this become an unquestioned best practice? 为什么这成为一个毫无疑问的最佳实践?

Declaring Underscore and jQuery as dependencies when you don't explicitly need them as variables in your module doesn't serve any purpose (ie it is not a best practice). 当您没有明确地将它们作为模块中的变量需要将Underscore和jQuery声明为依赖项时,它不会用于任何目的(即它不是最佳实践)。 As you said in your question 正如你在问题中所说

Personally, I would define jQuery or Underscore in a file that explicitly used their functions--but in something like a simple no-frills Backbone model file, they seem like cruft. 就个人而言,我会在一个明确使用其功能的文件中定义jQuery或Underscore - 但是在一个简单的简洁的Backbone模型文件中,它们看起来像是残酷的。

Moreover, you can even get rid of them in some situations: 而且,你甚至可以在某些情况下摆脱它们:

It's done only because of avoiding using global variables. 这只是因为避免使用全局变量。 Of course you can skip defining jQuery and underscore but $ and _ will refer to the global variables in this case. 当然你可以跳过定义jQuery和下划线但在这种情况下$_将引用全局变量。 In case you create your own application and use single version of jQuery - it will not case issues, but if your application already includes few different library versions - it's better to follow practice you do not like to follow :) 如果您创建自己的应用程序并使用单个版本的jQuery - 它不会出现案例问题,但如果您的应用程序已经包含很少的不同库版本 - 最好按照练习您不喜欢关注:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM