Kar*_*hik 5 javascript requirejs backbone.js
我在GitHub中查看Backbone-requireJS样板,我看到了两种不同类型的实现.
https://github.com/david0178418/BackboneJS-AMD-Boilerplate/blob/master/src/js/views/viewStub.js具有以下作为viewStub:
function() {
"use strict";
define([
'jqueryLoader',
'underscore',
'backbone',
],
function($, _, Backbone) {
return Backbone.View.extend({
template : _.template(/*loaded template*/),
initialize : function() {
this.render();
},
render : function() {
$(this.el).append(this.template(/*model/collection*/));
return this;
}
});
}
);
})();
Run Code Online (Sandbox Code Playgroud)
而来自其他样板的视图存根 https://github.com/jcreamer898/RequireJS-Backbone-Starter/blob/master/js/views/view.js具有以下内容:
define([
'jquery',
'backbone',
'underscore',
'models/model',
'text!templates/main.html'],
function($, Backbone, _, model, template){
var View = Backbone.View.extend({
el: '#main',
initialize: function(){
this.model = new model({
message: 'Hello World'
});
this.template = _.template( template, { model: this.model.toJSON() } );
},
render: function(){
$(this.el).append( this.template );
}
});
return new View();
});
Run Code Online (Sandbox Code Playgroud)
我的问题是: 为什么在第一个例子中围绕整个RequireJS模块有自动执行功能?
本例中不需要包含闭包。它创建一个作用域,以便声明的变量或函数不会泄漏到全局作用域中。但是,当您不创建变量或命名函数时,就不会泄漏任何内容。所以没有太多意义。
真正的原因可能比你想象的要简单。就像即使周围没人也使用转向灯一样,将每个 JS 源文件包含在一个自执行函数中是一个值得养成的好习惯。它可以让你避免犯愚蠢的错误。所以这可能只是防御性编程风格的一个例子。
此示例没有任何好处,但运行时的相关性能成本完全可以忽略不计。那么为什么不以“正确”的方式来做呢,以防万一有新的人进来并以某种时髦的方式“维护”这个模块呢?
| 归档时间: |
|
| 查看次数: |
1301 次 |
| 最近记录: |