Java开发主要由Backbone,Spine和jQuery(惊奇!)之类的库主导。 但是,这不是使用哪个库的问题,而是如何使用它的问题。
了解一些框架如何为看似不确定的javascript脚本提供脚手架和体系结构可能是我们的javascript技巧库中的关键组成部分。 通过让开发人员在逻辑上将关注点和依赖项分离开来,掌握这些知识从根本上打开了创建真正出色且身临其境的Web应用程序的最后一扇门。
在本文中,我们将逐步介绍一些基本的JavaScript模式:
- IIFE模块
- Dojo模块
- jQuery模块
- AMD模块
- CommonJS模块
- 外墙图案
- 中介模块
模块模式-立即调用的表达式函数(IIEF)使用执行上下文来创建隐私。
var module = (function(){
/**
* private variables are declared only inside the module
*/
var basket = [];
/**
* public variables are declared in the returned object
*/
return {
add: function(value){ ... },
count: function() { ... }
};
}());
module.add('a');
module.add('b');
module.add('c');
var total = module.count();
模块模式– Dojo
/**
* traditional method
*/
var store = window.store || {};
store.basket = store.basket || {};
/**
* dojo method
*/
dojo.setObject("store.basket.object", function(){
var basket = [];
function privateFunc(){ ... }
return {
add: function(value){ ... },
count: function(){ ... }
}
});
模块模式– jQuery
function library(module) {
$(function(){
if (module.init) {
module.init();
}
});
return module;
}
var myLibrary = library(
function(){
return {
init: function() {
/*implementation*/
}
};
}()
);
更好–异步模块定义或AMD
/**
* AMD: define()
* define a signature with define(id /*optional*/, [dependencies], /*factory module instantiation of fn*/);
*/
define(
/*module id*/
'myModule',
/*dependencies*/
['foo', 'bar;, 'baz'],
/*definition for the module export*/
function(foo, bar, baz){
/*module object*/
var module = {};
/*module methods go here*/
module.hello = foo.getSomething();
module.goodbye = bar.getSomething();
/*return the defined module object*/
return module;
}
);
/**
* AMD: require()
* load top-level code for JS files or inside modules for dynamically fetching dependencies
*/
/* top-level: the module exports (one, two) are passed as function arguments ot the object */
require(['one', 'two'], function(one, two){
...
});
/*inside: the complete example*/
define('three', ['one', 'two'], function(one, two){
/**
* require('string') can be used inside the function to get the module export
* of a module that has already been fetched and evaluated
*/
var temp = require('one');
/*this will fail*/
var four = require('four');
/* return a value to define the module export */
return function(){ ... };
});
最好:CommonJS –被广泛采用的服务器端格式
/**
* basically contains two parts: an exports object that contains the objects a module wishes to expose
* and a require function that modules can use to import the exports of other modules
*/
/* here we achieve compatibility with AMD and CommonJS using some boilerplate around the CommonJS module format*/
(function(define){
define(function(require,exports){
/*module contents*/
var dep1 = require("foo");
var dep2 = require("bar");
exports.hello = function(){...};
exports.world = function(){...};
});
})( typeof define=="function" ? define : function(factory){ factory(require, exports) });
** Harmonious revelations: ES Harmony, the the successor to ECMAScript 5
/**
* 1. static scoping
* 2. simple
* 3. reusable modules
*/
// Basic module
module SafeWidget {
import alert from Widget;
var _private ="someValue";
// exports
export var document = {
write: function(txt) {
alert('Out of luck, buck');
},
...
};
}
// Remote module
module JSONTest from 'http://json.org/modules/json2.js';
模块的替代模式
模块通常在MVC应用程序中使用。.但是还有其他一些模式也可以使大型应用程序的构建变得更加容易。请记住,jQuery在大型应用程序中的作用通常比大多数人想象的要小。 2nd.MD日历和预订代码,以及聊天门户,无需jQuery即可轻松操作。
外观–与大型代码主体的高级接口,掩盖了极其复杂的大部分信息
“当您放置外墙时,通常会创建一个隐藏了不同现实的外观。 认为它可以简化提供给其他开发人员的API”
基本的JavaScript设计模式
- 通过有限,更简单的API简化使用
- 隐藏库的内部结构,使实现的重要性降低
- 让您在幕后更有创造力
- 具有许多功能行为以确保应用程序安全
var module = (function() {
var _private = {
i:5,
get : function() {
console.log('current value:' + this.i);
},
set : function( val ) {
this.i = val;
},
run : function() {
console.log('running');
},
jump: function(){
console.log('jumping');
}
};
/**
* this part includes code imported above and provides an API to the returning module
*/
return {
facade : function( args ) {
_private.set(args.val);
_private.get();
if ( args.run ) {
_private.run();
}
}
};
}());
module.facade({run: true, val:10}); //outputs current value: 10, running
介体–通过为模块可以订阅的事件建立接口来促进松散耦合:
- 允许模块广播或侦听通知,而无需担心系统或繁琐的回调链。
- 通知可以一次由任意数量的模块异步处理。
- 由于代码的松散耦合性质,因此随时可以轻松添加或删除功能。
var mediator = (function(){
var subscribe = function(channel, fn){
if (!mediator.channels)mediator.channels = [];
mediator.channels.push({ context: this, callback:fn });
return this;
},
publish = function(channel){
if (!mediator.channels) return false;
var args = Array.prototype.slice.call(arguments, 1);
for (var i = 0, l = mediator.channels.length; i<l; i++) {
var subscription = mediator.channels[i];
subscription.callback.apply(subscription.context,args);
}
return this;
};
return {
channels: {},
publish: publish,
subscribe: subscribe,
installTo: function(obj){
obj.subscribe = subscribe;
obj.publish = publish;
}
};
}());
到此为止! 请记住,您如何组织代码和设计应用程序实际上可以将复杂的程序简化为几乎自然的本能。 对这些方法进行磨练,您将掌握真正成长为开发人员所需的技术!
From: https://www.sitepoint.com/javascript-application-design-patterns/