- 浏览: 3545857 次
- 性别:
- 来自: 大连
博客专栏
-
使用Titanium Mo...
浏览量:38094
-
Cordova 3.x入门...
浏览量:607081
-
常用Java开源Libra...
浏览量:682020
-
搭建 CentOS 6 服...
浏览量:89199
-
Spring Boot 入...
浏览量:401675
-
基于Spring Secu...
浏览量:69650
-
MQTT入门
浏览量:91646
文章分类
最新评论
-
afateg:
阿里云的图是怎么画出来的?用什么工具?
各云服务平台的架构图 -
cbn_1992:
博主,采用jdbctoken也就是数据库形式之后,反复点击获取 ...
Spring Security OAuth2 Provider 之 数据库存储 -
ipodao:
写的很是清楚了,我找到一份中文协议:https://mcxia ...
MQTT入门(6)- 主题Topics -
Cavani_cc:
还行
MQTT入门(6)- 主题Topics -
fexiong:
博主,能否提供完整源码用于学习?邮箱:2199611997@q ...
TensorFlow 之 构建人物识别系统
【官方地址】https://wiki.appcelerator.org/display/guides/CommonJS+Modules+in+Titanium
Synopsis
Titanium Mobile is moving toward the adoption of the CommonJS module specification as the way in which end users of the platform structure their JavaScript code. While CommonJS Modules are a "standard" specification, there are differences in implementation across multiple technology stacks. The aim of this specification is to delineate what is and is not supported by the Titanium Mobile implementation of this spec, starting in 1.8 and moving forward.
Definitions
CommonJS Module Spec Implementation
Our specific implementation of the CommonJS Module Specification is based on (and the early implementation on Android taken directly from) that of node.js. While we should not consider our implementation a direct clone of node, we should favor node conventions where possible to foster reuse of modules across both environments.
Simple Usage
In order to use a module within Titanium, you must use the require function, which is built in to the global scope in every JavaScript context.
The string passed to require must be resolvable to either a native/compiled module that Titanium Mobile has access to, or a JavaScript module provided in the Resources directory of the Titanium Mobile application. The require function returns an JavaScript object, with properties, functions, and other data assigned to it which form the public interface to the module. If the module we loaded into the application above exposed a function sayHello, which would print a name and a welcome message to the console, it would be accessed in this way:
Native/Compiled versus JavaScript Modules
When a module is required, Titanium must first determine whether or not to load a native/compiled module or a JavaScript module shipped within the Resources directory of a Titanium Mobile application. Titanium will prefer to load a native module first. The deployment and processing of native modules is beyond the scope of this specification, but at the time of this writing, native modules can be deployed globally on a developer machine, or inside a modules directory in the top-level Titanium Mobile project directory.
Native/Compiled Modules
Native/compiled modules are identified by a single string, specified within the global app configuration in tiapp.xml. Given the following configuration for a native/compiled module in tiapp.xml:
and the following code within a Titanium Mobile application:
Titanium will load the ti.paypal native module, and will NOT attempt to look for or load a module from Resources. If a native module is not found for the string passed to require, Titanium will look for a JavaScript module in the Resources.
JavaScript Modules
Modules may also be loaded as JavaScript files from the Resources directory of the application. In Titanium Mobile, a JavaScript module is associated with a single JavaScript file. When the module is loaded, the JavaScript file will be evaluated and the public interface of the module will be populated.
JavaScript Module Path Resolution
When dealing with JavaScript modules from Resources, the string passed to require is considered to be a path to the JavaScript file, minus the ".js" extension. If the path string is not prefixed by a ./, ../, or similar, it is assumed that the module is being referenced relative to the Resources directory. In a Titanium project with a CommonJS module file located in Resources/app/lib/myModule.js, that module could be loaded as such: var myModule = require('app/lib/myModule');.
Similarly, if the path is prefixed with a /, the module path is also resolved relative to the Resources directory. For the module above, another valid loading syntax would be var myModule = require('/app/lib/myModule');.
Relative paths may be specified as well. Assume we have modules located in the following locations:
Now assume we are writing code inside the SomeCustomView.js module file. The following are valid require statements:
SomeCustomView.js
JavaScript Module Composition
As in the CommonJS Module specification, inside the module JavaScript file, there will be a special variable called exports to which properties may be added for the public interface of the module.
As many properties as desired can be added to the exports object.
Alternately, if the module author wishes to make the exported value from the module an object of their own design and choosing, there is a non-standard (but common, as with node.js) extension to the Module specification which allows for this. The module.exports object is available within the module file, and may be assigned any value which the developer would like to return from the require function for their module. This is most commonly used for functions which act as object constructors. The following would be a typical use case for this:
Usage:
Resources/app.js
Antipatterns and Unsupported Behavior
No direct assignments may be made to the exports object:
Similarly, you should not mix and match usage of module.exports and exports.*:
Also, it is recommended that you not mix and match assignments to module.exports and exports - use one or the other:
Caching
When a JavaScript module is loaded, the object returned by require should be cached by Titanium and provided again to consumers without evaluating the module's JavaScript code multiple times. If a developer thinks they want their module code evaluated multiple times, they should really be creating a module with a function that can be called multiple times. There's no valid use case for re-evaluating JavaScript in a module over and over.
Security and Sandboxing
As in the CommonJS Module specification, all modules have their own private scope. Variables declared within the module file are private - anything that needs to be made public should be added to the exports object. For more information on sandboxing, refer to the CommonJS module spec.
Stateful Modules
All modules in Titanium are created once, and then passed by reference on subsequent occasions when the module is required. Because of this, modules themselves may have state variables, which are properties of the "singleton" object represented by the module.
app.js
scoreModule.js
statefulModule.js
NOTE: A module is created once per Titanium JavaScript context, so if additional contexts are created, new module objects will be created. For more on JavaScript contexts, see here.
Global Variables
There shall not be ANY global variables in a Titanium application shared across all modules. Any data a module or any objects exposed by a module require should be passed in during construction or initialization.
JavaScript Module Examples
Here are some examples of modules we expect developers to implement:
Utility Libraries
logger.js
Usage:
Packages of Related Functionality
geo.js
Usage:
Instantiable Objects
Person.js
Usage:
Synopsis
Titanium Mobile is moving toward the adoption of the CommonJS module specification as the way in which end users of the platform structure their JavaScript code. While CommonJS Modules are a "standard" specification, there are differences in implementation across multiple technology stacks. The aim of this specification is to delineate what is and is not supported by the Titanium Mobile implementation of this spec, starting in 1.8 and moving forward.
Definitions
- Module - Any CommonJS-compliant module which will be consumed in a Titanium Mobile application. This can be a JavaScript file included with an application, or a native extension to Titanium which exposes a JavaScript API.
- Resources - The Resources directory of a Titanium application, where the user's source code lives before any processing by our build system.
- exports - a free variable within a module, to which multiple properties may be added to create a public interface
- module.exports - an object within a module, which may be REPLACED by an object representing the public interface to the module
CommonJS Module Spec Implementation
Our specific implementation of the CommonJS Module Specification is based on (and the early implementation on Android taken directly from) that of node.js. While we should not consider our implementation a direct clone of node, we should favor node conventions where possible to foster reuse of modules across both environments.
Simple Usage
In order to use a module within Titanium, you must use the require function, which is built in to the global scope in every JavaScript context.
var myModule = require('MyModule');
The string passed to require must be resolvable to either a native/compiled module that Titanium Mobile has access to, or a JavaScript module provided in the Resources directory of the Titanium Mobile application. The require function returns an JavaScript object, with properties, functions, and other data assigned to it which form the public interface to the module. If the module we loaded into the application above exposed a function sayHello, which would print a name and a welcome message to the console, it would be accessed in this way:
var myModule = require('MyModule'); myModule.sayHello('Kevin'); //console output is "Hello Kevin!"
Native/Compiled versus JavaScript Modules
When a module is required, Titanium must first determine whether or not to load a native/compiled module or a JavaScript module shipped within the Resources directory of a Titanium Mobile application. Titanium will prefer to load a native module first. The deployment and processing of native modules is beyond the scope of this specification, but at the time of this writing, native modules can be deployed globally on a developer machine, or inside a modules directory in the top-level Titanium Mobile project directory.
Native/Compiled Modules
Native/compiled modules are identified by a single string, specified within the global app configuration in tiapp.xml. Given the following configuration for a native/compiled module in tiapp.xml:
<modules> <module version="1.0">ti.paypal</module> </modules>
and the following code within a Titanium Mobile application:
var paypal = require('ti.paypal');
Titanium will load the ti.paypal native module, and will NOT attempt to look for or load a module from Resources. If a native module is not found for the string passed to require, Titanium will look for a JavaScript module in the Resources.
JavaScript Modules
Modules may also be loaded as JavaScript files from the Resources directory of the application. In Titanium Mobile, a JavaScript module is associated with a single JavaScript file. When the module is loaded, the JavaScript file will be evaluated and the public interface of the module will be populated.
JavaScript Module Path Resolution
When dealing with JavaScript modules from Resources, the string passed to require is considered to be a path to the JavaScript file, minus the ".js" extension. If the path string is not prefixed by a ./, ../, or similar, it is assumed that the module is being referenced relative to the Resources directory. In a Titanium project with a CommonJS module file located in Resources/app/lib/myModule.js, that module could be loaded as such: var myModule = require('app/lib/myModule');.
Similarly, if the path is prefixed with a /, the module path is also resolved relative to the Resources directory. For the module above, another valid loading syntax would be var myModule = require('/app/lib/myModule');.
Relative paths may be specified as well. Assume we have modules located in the following locations:
- Resources/app/ui/SomeCustomView.js
- Resources/app/ui/widgets/SomeOtherCustomView.js
- Resources/app/lib/myModule.js
Now assume we are writing code inside the SomeCustomView.js module file. The following are valid require statements:
SomeCustomView.js
var myModule = require('../lib/myModule'); var SomeOtherCustomView = require('./widgets/SomeOtherCustomView');
JavaScript Module Composition
As in the CommonJS Module specification, inside the module JavaScript file, there will be a special variable called exports to which properties may be added for the public interface of the module.
exports.sayHello = function(name) { Ti.API.info('Hello '+name+'!'); }; exports.version = 1.4; exports.author = 'Don Thorp';
As many properties as desired can be added to the exports object.
Alternately, if the module author wishes to make the exported value from the module an object of their own design and choosing, there is a non-standard (but common, as with node.js) extension to the Module specification which allows for this. The module.exports object is available within the module file, and may be assigned any value which the developer would like to return from the require function for their module. This is most commonly used for functions which act as object constructors. The following would be a typical use case for this:
function Person(firstName,lastName) { this.firstName = firstName; this.lastName = lastName; } Person.prototype.fullName = function() { return this.firstName+' '+this.lastName; }; module.exports = Person;
Usage:
Resources/app.js
var Person = require('Person'); var don = new Person('Don','Thorp'); var donsName = don.fullName(); // "Don Thorp" Antipatterns and Unsupported Behavior
Antipatterns and Unsupported Behavior
No direct assignments may be made to the exports object:
function Person(firstName,lastName) { this.firstName = firstName; this.lastName = lastName; } exports = Person; //THIS IS NOT OK AND PROBABLY WON'T WORK
Similarly, you should not mix and match usage of module.exports and exports.*:
function Person(firstName,lastName) { this.firstName = firstName; this.lastName = lastName; } module.exports = Person; //This is okay, but... exports.foo = 'bar'; //This is discouraged - use one or the other
Also, it is recommended that you not mix and match assignments to module.exports and exports - use one or the other:
exports.foo = 'bar'; module.exports.fooToo = 'something else'; // Not good style - use one or the other.
Caching
When a JavaScript module is loaded, the object returned by require should be cached by Titanium and provided again to consumers without evaluating the module's JavaScript code multiple times. If a developer thinks they want their module code evaluated multiple times, they should really be creating a module with a function that can be called multiple times. There's no valid use case for re-evaluating JavaScript in a module over and over.
Security and Sandboxing
As in the CommonJS Module specification, all modules have their own private scope. Variables declared within the module file are private - anything that needs to be made public should be added to the exports object. For more information on sandboxing, refer to the CommonJS module spec.
Stateful Modules
All modules in Titanium are created once, and then passed by reference on subsequent occasions when the module is required. Because of this, modules themselves may have state variables, which are properties of the "singleton" object represented by the module.
app.js
var stateful = require('statefulModule'); var score = require('scoreModule'); var window = Ti.UI.createWindow({ backgroundColor:'white', fullscreen:false, title:'Click window to score' }); window.addEventListener('click', function() { try { Ti.API.info("The latest score is " + score.latestScore()); Ti.API.info("Adding " + stateful.getPointStep() + " points to score..."); score.pointsWon(); Ti.API.info("The latest score is " + score.latestScore()); Ti.API.info("Setting points per win to 10"); stateful.setPointStep(10); Ti.API.info("Adding " + stateful.getPointStep() + " points to score..."); score.pointsWon(); Ti.API.info("The latest score is " + score.latestScore()); Ti.API.info("---------- Info ----------"); Ti.API.info("stateful.getPointStep() returns: " + stateful.getPointStep()); Ti.API.info("stateful.stepVal value is: " + stateful.stepVal); // will always return default of 5 Ti.API.info("**************************"); } catch(e) { alert("An error has occurred: " + e); } }); window.open();
scoreModule.js
var appStateful = require('statefulModule'); // a reference to the "stateful" variable in app.js that contains the stateful module var _score = 0; // default exports.pointsWon = function() { _score += appStateful.getPointStep(); }; exports.pointsLost = function() { _score -= appStateful.getPointStep(); }; exports.latestScore = function() { return _score; };
statefulModule.js
var _stepVal = 5; // default exports.setPointStep = function(value) { _stepVal = value; }; exports.getPointStep = function() { return _stepVal; }; exports.stepVal = _stepVal;
NOTE: A module is created once per Titanium JavaScript context, so if additional contexts are created, new module objects will be created. For more on JavaScript contexts, see here.
Global Variables
There shall not be ANY global variables in a Titanium application shared across all modules. Any data a module or any objects exposed by a module require should be passed in during construction or initialization.
JavaScript Module Examples
Here are some examples of modules we expect developers to implement:
Utility Libraries
logger.js
exports.info = function(str) { Titanium.API.info(new Date()+': '+str); }; exports.debug = function(str) { Titanium.API.debug(new Date()+': '+str); };
Usage:
var logger = require('logger'); logger.info('some log statement I wanted with a timestamp');
Packages of Related Functionality
geo.js
function Point(x,y) { this.x = x; this.y = y; } function Line(start,end) { this.start = start; this.end = end; } Line.prototype.slope = function() { return (this.end.y - this.start.y) / (this.end.x - this.start.x); }; Line.prototype.yIntercept = function() { return this.start.y - (this.slope()*this.start.x); }; //create public interface exports.Point = Point; exports.Line = Line;
Usage:
var geo = require('lib/geo'); var startPoint = new geo.Point(1,-5); var endPoint = new geo.Point(10,2); var line = new geo.Line(startPoint,endPoint); var slopeValue = line.slope();
Instantiable Objects
Person.js
function Person(firstName,lastName) { this.firstName = firstName; this.lastName = lastName; } Person.prototype.fullName = function() { return this.firstName+' '+this.lastName; }; module.exports = Person;
Usage:
var Person = require('Person'); var don = new Person('Don','Thorp'); var donsName = don.fullName(); // "Don Thorp"
发表评论
-
VisualUI for Titanium Studio
2014-01-13 09:02 1542VisualUI for Titanium Studio is ... -
Google Auth (OAuth 2.0) for Titanium
2013-03-19 11:49 2049Google OAuth 2.0 for Titanium i ... -
Appcelerator Titanium: Up and Running
2013-03-19 08:40 46Appcelerator Titanium: Up and R ... -
Titanium SDK/Studio 3.0.0 Beta版发布
2012-11-07 09:36 463Titanium SDK/Studio 3.0.0 Beta版 ... -
Titanium SDK 3.0.0 Developer Preview
2012-10-29 16:15 303Titanium SDK 3.0.0 Developer Pr ... -
Appcelerator Partners With Largest Chinese Software Developer Network
2012-10-29 12:01 225(Marketwire - Oct 19, 2012) -Ap ... -
Titanium 3.0 预定10月份发布
2012-09-27 09:12 733Appcelerator CEO Jeff Haynie和 C ... -
Titanium SDK 2.1.3 RC is released – Support for iOS 6
2012-09-21 13:51 241---以下官方原文--- We understand the ... -
国内Ti开发者Winson的CBMVC框架
2012-08-06 15:55 1206目前关注Titanium的开发 ... -
Titanium的MVC框架"Alloy"的介绍
2012-07-18 14:37 4250Alloy(合金)是Appcelerator公司为Titani ... -
TCAD免费考试延长至7月末
2012-07-17 16:09 327Appcelerator延长这次TCAD免费考试的时间到7月末 ... -
TCAD认证考试
2012-07-13 11:31 2556Appcelerator从7/7开始免费开放TCAD(Tita ... -
【转】Appcelerator Cloud Push Notification in iPhone
2012-07-12 08:49 2760Push Notification in iOS Using ... -
【转】Appcelerator Cloud Push Notification in Android
2012-07-12 08:38 2483What is Push Notification? Push ... -
Appcelerator Titanium: Patterns and Best Practices
2012-07-10 10:58 373Appcelerator Titanium: Patterns ... -
Appceleator Cloud Services使用指南(3) - API Reference V1 (chm版本)
2012-05-28 15:22 1863Appceleator Cloud Services API ... -
Appceleator Cloud Services使用指南(2) - 创建第一个应用
2012-05-24 21:57 1780一步一步的创建一个最简单的,使用了ACS服务的应用。 1、新 ... -
Appceleator Cloud Services使用指南(1) - ACS介绍
2012-05-24 10:19 3259Appceleator Cloud Services( ... -
Titanium Mobile基础教程视频
2012-05-23 10:38 639dotinstall.com提供的一套在线Titanium M ... -
Jeff Haynie在GMIC2012表示应用开发者应注意本土化问题
2012-05-22 16:56 3355月10日-11日,2012全球移 ...
相关推荐
nashorn-commonjs-modules, CommonJS的模块支持 Nashorn CommonJS模块支持 Nashorn这个库增加了对CommonJS模块( aka require ) inside的支持( Nashorn脚本引擎) 。 它基于 NodeJS模块的规范,它支持从文件夹加载模块...
Titanium.ImageCache是一个专门为Titanium SDK设计的CommonJS模块,其主要目的是优化应用程序的性能,特别是在处理大量图像加载时。这个模块提供了一种高效的图片缓存机制,避免了每次需要显示图片时都从网络下载,...
** 编写了一个很棒的 commonjs 模块 ,用于在 Appcelerator Titanium 应用程序中实现 commonjs。 他的模块只有两个变化: 为了使用框架,我们需要控制这段代码的运行时间,所以模块被分成了两个不同的包: -- 一个...
Appcelerator Titanium CommonJS 模块的基于的生成器。 入门 首先确保安装了 yo 和 和 生成器: $ npm install -g yo generator-titanium-commonjs 您可能需要具有 sudo 权限才能全局安装。 之后,您可以通过创建...
ti-commonjs 通过 Alloy 在 Appcelerator Titanium 中使用 Node.js 风格的 CommonJS。 有关这究竟意味着什么的完整详细信息,请查看 Node.js 自己。 除了这个附加功能之外, ti-commonjs还消除了 Titanium 的 ...
扩展的EXTJS公共类,扩展的EXTJS公共类,扩展的EXTJS公共类
扩展的EXTJS公共类,扩展的EXTJS公共类,扩展的EXTJS公共类
扩展的EXTJS公共类,扩展的EXTJS公共类,扩展的EXTJS公共类
扩展的EXTJS公共类,扩展的EXTJS公共类,扩展的EXTJS公共类
CommonJS和ESM(ECMAScript Modules)是两种主要的模块规范。CommonJS是Node.js环境中广泛使用的模块化标准,而ESM则是ES6引入的原生模块系统,适用于浏览器和Node.js。本篇文章将深入探讨Babel 7中的转换插件,特别...
rollup-plugin-commonjs, 将CommonJS模块转换为 ES2015 rollup-plugin-commonjs 将CommonJS模块转换为 ES6,以便它们可以包含在Rollup包中安装npm install --save-dev rollup-plugin-commonjs用法
扩展的EXTJS公共类,扩展的EXTJS公共类,扩展的EXTJS公共类
CommonJS和ES Modules(ESM)是两种常见的模块规范,它们各自有着不同的工作原理和应用场景。在本篇文章中,我们将通过使用webpack来深入理解这两者的差异。 首先,CommonJS是Node.js中的默认模块系统,它基于同步...
CommonJS是一种在服务器端JavaScript中实现模块化的规范,它的出现主要是为了标准化服务器端JavaScript模块的加载机制。CommonJS规范最初于2009年提出,它的设计理念是基于同步加载机制,并且以文件为模块的载体。在...
在JavaScript的开发环境中,我们经常会遇到各种错误,其中之一就是“Error in ./node_modules/axios/lib/platform/index.js”。这个错误提示通常意味着在项目中使用axios库时遇到了问题。Axios是一款非常流行的基于...
commonjs-everywhere, 具有别名,可扩展性和源映射的CommonJS浏览器 bundler 到处都是 web浏览器使用从缩小的JS包到原始源的源代码,浏览器替代的别名和任意语言支持的可扩展性。安装npm install -g commonjs-...
扩展的EXTJS公共类.扩展的EXTJS公共类.扩展的EXTJS公共类