alloy-howtos

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Titanium Alloy How-tos

Titanium Alloy 使用指南

Practical guide for Alloy MVC projects in the Titanium SDK.
Titanium SDK中Alloy MVC项目的实用指南。

Project detection

项目检测

:::info Auto-detects Alloy projects This skill checks for Alloy projects when invoked and provides CLI and configuration guidance.
Detection is automatic. No manual command is needed.
Alloy project indicators:
  • app/
    folder with Alloy structure
  • alloy.jmk
    or
    config.json
    files
Behavior based on detection:
  • Alloy detected -> Provide Alloy CLI command guidance, configuration file help, Alloy-specific troubleshooting
  • Not detected -> Explain this skill is for Alloy projects only and suggest Alloy guides if the user wants to migrate :::
:::info 自动检测Alloy项目 此技能在调用时会自动检测Alloy项目,并提供CLI和配置相关指导。
检测是自动进行的,无需手动执行命令。
Alloy项目的判定指标:
  • 包含Alloy结构的
    app/
    文件夹
  • 存在
    alloy.jmk
    config.json
    文件
根据检测结果的不同行为:
  • 检测到Alloy项目 -> 提供Alloy CLI命令指导、配置文件帮助以及Alloy专属问题排查方案
  • 未检测到Alloy项目 -> 说明此技能仅适用于Alloy项目,若用户想要迁移项目,会提供Alloy相关指南建议 :::

Quick reference

快速参考

TopicReference
Best Practices & Naming Conventionsbest_practices.md
CLI Commands (new, generate, compile)cli_reference.md
Configuration Files (alloy.jmk, config.json)config_files.md
Custom XML Tags & Reusable Componentscustom_tags.md
Debugging & Common Errorsdebugging_troubleshooting.md
Code Samples & Conditionalssamples.md
主题参考文档
最佳实践与命名规范best_practices.md
CLI命令(new、generate、compile)cli_reference.md
配置文件(alloy.jmk、config.json)config_files.md
自定义XML标签与可复用组件custom_tags.md
调试与常见错误debugging_troubleshooting.md
代码示例与条件渲染samples.md

Key practices

关键实践

Naming conventions

命名规范

  • Never use double underscore prefixes (
    __foo
    ) - reserved for Alloy
  • Never use JavaScript reserved words as IDs
  • 切勿使用双下划线前缀
    __foo
    )- 该前缀为Alloy保留
  • 切勿将JavaScript保留字用作ID

Global events - use Backbone.Events

全局事件 - 使用Backbone.Events

Avoid
Ti.App.fireEvent
/
Ti.App.addEventListener
. It can cause memory leaks and poor performance.
Use the Backbone.Events pattern:
javascript
// In alloy.js
Alloy.Events = _.clone(Backbone.Events);

// Listener
Alloy.Events.on('updateMainUI', refreshData);
// Clean up on close
$.controller.addEventListener('close', () => {
    Alloy.Events.off('updateMainUI');
});

// Trigger
Alloy.Events.trigger('updateMainUI');
避免使用
Ti.App.fireEvent
/
Ti.App.addEventListener
,这可能会导致内存泄漏和性能问题。
请使用Backbone.Events模式:
javascript
// In alloy.js
Alloy.Events = _.clone(Backbone.Events);

// Listener
Alloy.Events.on('updateMainUI', refreshData);
// Clean up on close
$.controller.addEventListener('close', () => {
    Alloy.Events.off('updateMainUI');
});

// Trigger
Alloy.Events.trigger('updateMainUI');

Global variables in non-controller files

非控制器文件中的全局变量

Always require Alloy modules:
javascript
const Alloy = require('alloy');
const Backbone = require('alloy/backbone');
const _ = require('alloy/underscore')._;
始终引入Alloy模块:
javascript
const Alloy = require('alloy');
const Backbone = require('alloy/backbone');
const _ = require('alloy/underscore')._;

Conditional views

条件视图

Use
if
attributes in XML for conditional rendering (evaluated before render):
xml
<Alloy>
    <Window>
        <View if="Alloy.Globals.isLoggedIn()" id="notLoggedIn">
             <Label text="Not logged in" />
        </View>
        <View if="!Alloy.Globals.isLoggedIn()" id="loggedIn">
            <Label text="Logged in" />
        </View>
    </Window>
</Alloy>
Conditional TSS styles:
tss
"#info[if=Alloy.Globals.isIos7Plus]": {
    font: { textStyle: Ti.UI.TEXT_STYLE_FOOTNOTE }
}
Data-binding conditionals:
xml
<TableViewRow if="$model.shouldShowCommentRow()">
在XML中使用
if
属性实现条件渲染(渲染前进行求值):
xml
<Alloy>
    <Window>
        <View if="Alloy.Globals.isLoggedIn()" id="notLoggedIn">
             <Label text="Not logged in" />
        </View>
        <View if="!Alloy.Globals.isLoggedIn()" id="loggedIn">
            <Label text="Logged in" />
        </View>
    </Window>
</Alloy>
条件TSS样式:
tss
"#info[if=Alloy.Globals.isIos7Plus]": {
    font: { textStyle: Ti.UI.TEXT_STYLE_FOOTNOTE }
}
数据绑定条件:
xml
<TableViewRow if="$model.shouldShowCommentRow()">

Common error solutions

常见错误解决方案

ErrorSolution
No app.js found
Run
alloy compile --config platform=<platform>
Android assets not showingUse absolute paths (prepend
/
)
Alloy is not defined
(non-controller)
Add
const Alloy = require('alloy');
iOS
invalid method passed to UIModule
Creating Android-only object - use
platform
attribute
错误信息解决方案
No app.js found
运行
alloy compile --config platform=<platform>
Android资源不显示使用绝对路径(添加前缀
/
Alloy is not defined
(非控制器文件中)
添加
const Alloy = require('alloy');
iOS
invalid method passed to UIModule
创建了仅支持Android的对象 - 使用
platform
属性

CLI quick reference

CLI快速参考

bash
undefined
bash
undefined

New project

New project

alloy new [path] [template]
alloy new [path] [template]

Generate components

Generate components

alloy generate controller <name> alloy generate model <name> <adapter> <schema> alloy generate style --all
alloy generate controller <name> alloy generate model <name> <adapter> <schema> alloy generate style --all

Compile

Compile

alloy compile [--config platform=android,deploytype=test]
alloy compile [--config platform=android,deploytype=test]

Extract i18n strings

Extract i18n strings

alloy extract-i18n en --apply
alloy extract-i18n en --apply

Copy/move/remove controllers

Copy/move/remove controllers

alloy copy <old> <new> alloy move <old> <new> alloy remove <name>
undefined
alloy copy <old> <new> alloy move <old> <new> alloy remove <name>
undefined

Configuration files priority

配置文件优先级

config.json precedence:
os:ios
>
env:production
>
global
Access at runtime:
Alloy.CFG.yourKey
config.json的优先级:
os:ios
>
env:production
>
global
运行时访问方式:
Alloy.CFG.yourKey

Custom XML tags

自定义XML标签

Create reusable components without widgets. Drop a file in
app/lib/
:
app/lib/checkbox.js
javascript
exports.createCheckBox = args => {
    const wrapper = Ti.UI.createView({ layout: "horizontal", checked: false });
    const box = Ti.UI.createView({ width: 15, height: 15, borderWidth: 1 });
    // ... build component, return Ti.UI.* object
    return wrapper;
};
view.xml
xml
<CheckBox module="checkbox" id="terms" caption="I agree" onChange="onCheck" />
Key: the
module
attribute points to the file in
app/lib/
(without
.js
). The function must be
create<TagName>
.
See custom_tags.md for complete examples.
无需使用widget即可创建可复用组件。在
app/lib/
目录下创建文件:
app/lib/checkbox.js
javascript
exports.createCheckBox = args => {
    const wrapper = Ti.UI.createView({ layout: "horizontal", checked: false });
    const box = Ti.UI.createView({ width: 15, height: 15, borderWidth: 1 });
    // ... build component, return Ti.UI.* object
    return wrapper;
};
view.xml
xml
<CheckBox module="checkbox" id="terms" caption="I agree" onChange="onCheck" />
关键要点:
module
属性指向
app/lib/
目录下的文件(无需
.js
后缀),函数名称必须为
create<TagName>
查看custom_tags.md获取完整示例。

Resources

资源

references/

参考文档/

Reference docs by topic:
  • best_practices.md - Coding standards, naming conventions, global events patterns
  • cli_reference.md - All CLI commands with options and model schema format
  • config_files.md - alloy.jmk tasks, config.json structure, widget.json format
  • custom_tags.md - Creating reusable custom XML tags without widgets
  • debugging_troubleshooting.md - Common errors with solutions
  • samples.md - Controller examples, conditional views, data-binding patterns
按主题分类的参考文档:
  • best_practices.md - 编码标准、命名规范、全局事件模式
  • cli_reference.md - 所有CLI命令及其选项、模型schema格式
  • config_files.md - alloy.jmk任务、config.json结构、widget.json格式
  • custom_tags.md - 无需widget创建可复用自定义XML标签
  • debugging_troubleshooting.md - 常见错误及解决方案
  • samples.md - 控制器示例、条件视图、数据绑定模式

Related skills

相关技能

For tasks beyond Alloy CLI and configuration, use these related skills:
TaskUse This Skill
Modern architecture, services, patterns
ti-expert
Alloy MVC concepts, models, data binding
alloy-guides
SDK config, Hyperloop, app distribution
ti-guides
对于超出Alloy CLI和配置范畴的任务,可使用以下相关技能:
任务场景推荐使用的技能
现代架构、服务、设计模式
ti-expert
Alloy MVC概念、模型、数据绑定
alloy-guides
SDK配置、Hyperloop、应用分发
ti-guides