@maccesar/titools 2.10.1 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/AGENTS-VERCEL-RESEARCH.md +23 -12
  2. package/README.md +81 -182
  3. package/agents/ti-pro.md +8 -14
  4. package/lib/cleanup.js +13 -0
  5. package/lib/commands/skills.js +2 -1
  6. package/lib/config.js +9 -11
  7. package/lib/platform.js +1 -1
  8. package/package.json +2 -3
  9. package/skills/purgetss/SKILL.md +44 -57
  10. package/skills/purgetss/references/EXAMPLES.md +8 -1
  11. package/skills/purgetss/references/app-branding.md +96 -16
  12. package/skills/purgetss/references/apply-directive.md +26 -1
  13. package/skills/purgetss/references/arbitrary-values.md +72 -2
  14. package/skills/purgetss/references/class-categories.md +1 -1
  15. package/skills/purgetss/references/cli-commands.md +37 -13
  16. package/skills/purgetss/references/customization-deep-dive.md +18 -11
  17. package/skills/purgetss/references/dynamic-component-creation.md +0 -1
  18. package/skills/purgetss/references/migration-guide.md +162 -1
  19. package/skills/purgetss/references/multi-density-images.md +69 -0
  20. package/skills/purgetss/references/version-history.md +82 -0
  21. package/skills/ti-expert/SKILL.md +1 -1
  22. package/skills/ti-ui/SKILL.md +1 -1
  23. package/skills/alloy-guides/SKILL.md +0 -190
  24. package/skills/alloy-guides/references/CLI_TASKS.md +0 -233
  25. package/skills/alloy-guides/references/CONCEPTS.md +0 -171
  26. package/skills/alloy-guides/references/CONTROLLERS.md +0 -279
  27. package/skills/alloy-guides/references/MODELS.md +0 -1214
  28. package/skills/alloy-guides/references/PURGETSS.md +0 -46
  29. package/skills/alloy-guides/references/VIEWS_DYNAMIC.md +0 -235
  30. package/skills/alloy-guides/references/VIEWS_STYLES.md +0 -375
  31. package/skills/alloy-guides/references/VIEWS_WITHOUT_CONTROLLERS.md +0 -102
  32. package/skills/alloy-guides/references/VIEWS_XML.md +0 -581
  33. package/skills/alloy-guides/references/WIDGETS.md +0 -160
  34. package/skills/alloy-howtos/SKILL.md +0 -181
  35. package/skills/alloy-howtos/references/best_practices.md +0 -121
  36. package/skills/alloy-howtos/references/cli_reference.md +0 -230
  37. package/skills/alloy-howtos/references/config_files.md +0 -158
  38. package/skills/alloy-howtos/references/custom_tags.md +0 -148
  39. package/skills/alloy-howtos/references/debugging_troubleshooting.md +0 -78
  40. package/skills/alloy-howtos/references/samples.md +0 -156
  41. package/skills/ti-api/SKILL.md +0 -109
  42. package/skills/ti-api/references/api-android.md +0 -675
  43. package/skills/ti-api/references/api-app-platform.md +0 -636
  44. package/skills/ti-api/references/api-core.md +0 -764
  45. package/skills/ti-api/references/api-data-network.md +0 -641
  46. package/skills/ti-api/references/api-media.md +0 -655
  47. package/skills/ti-api/references/api-modules-ble-bluetooth.md +0 -657
  48. package/skills/ti-api/references/api-modules-coremotion-urlsession.md +0 -411
  49. package/skills/ti-api/references/api-modules-map.md +0 -632
  50. package/skills/ti-api/references/api-modules-nfc.md +0 -725
  51. package/skills/ti-api/references/api-modules-social-misc.md +0 -526
  52. package/skills/ti-api/references/api-services.md +0 -700
  53. package/skills/ti-api/references/api-ui-android.md +0 -499
  54. package/skills/ti-api/references/api-ui-extras.md +0 -702
  55. package/skills/ti-api/references/api-ui-ios-animator.md +0 -378
  56. package/skills/ti-api/references/api-ui-ios.md +0 -756
  57. package/skills/ti-api/references/api-ui-lists.md +0 -581
  58. package/skills/ti-api/references/api-ui-text-input.md +0 -607
  59. package/skills/ti-api/references/api-ui-views.md +0 -572
  60. package/skills/ti-api/references/api-ui-windows-navigation.md +0 -676
  61. package/skills/ti-api/references/api-xml-global.md +0 -743
  62. package/skills/ti-guides/SKILL.md +0 -75
  63. package/skills/ti-guides/references/advanced-data-and-images.md +0 -155
  64. package/skills/ti-guides/references/android-manifest.md +0 -97
  65. package/skills/ti-guides/references/app-distribution.md +0 -373
  66. package/skills/ti-guides/references/application-frameworks.md +0 -366
  67. package/skills/ti-guides/references/cli-reference.md +0 -700
  68. package/skills/ti-guides/references/coding-best-practices.md +0 -150
  69. package/skills/ti-guides/references/commonjs-advanced.md +0 -279
  70. package/skills/ti-guides/references/hello-world.md +0 -99
  71. package/skills/ti-guides/references/hyperloop-native-access.md +0 -458
  72. package/skills/ti-guides/references/javascript-primer.md +0 -402
  73. package/skills/ti-guides/references/reserved-words.md +0 -36
  74. package/skills/ti-guides/references/resources.md +0 -172
  75. package/skills/ti-guides/references/style-and-conventions.md +0 -104
  76. package/skills/ti-guides/references/tiapp-config.md +0 -655
  77. package/skills/ti-howtos/SKILL.md +0 -143
  78. package/skills/ti-howtos/references/android-platform-deep-dives.md +0 -609
  79. package/skills/ti-howtos/references/automation-fastlane-appium.md +0 -96
  80. package/skills/ti-howtos/references/buffer-codec-streams.md +0 -162
  81. package/skills/ti-howtos/references/cross-platform-development.md +0 -358
  82. package/skills/ti-howtos/references/debugging-profiling.md +0 -473
  83. package/skills/ti-howtos/references/extending-titanium.md +0 -684
  84. package/skills/ti-howtos/references/google-maps-v2.md +0 -172
  85. package/skills/ti-howtos/references/ios-map-kit.md +0 -149
  86. package/skills/ti-howtos/references/ios-platform-deep-dives.md +0 -595
  87. package/skills/ti-howtos/references/local-data-sources.md +0 -310
  88. package/skills/ti-howtos/references/location-and-maps.md +0 -267
  89. package/skills/ti-howtos/references/media-apis.md +0 -268
  90. package/skills/ti-howtos/references/notification-services.md +0 -539
  91. package/skills/ti-howtos/references/remote-data-sources.md +0 -339
  92. package/skills/ti-howtos/references/tutorials.md +0 -552
  93. package/skills/ti-howtos/references/using-modules.md +0 -182
  94. package/skills/ti-howtos/references/web-content-integration.md +0 -288
  95. package/skills/ti-howtos/references/webpack-build-pipeline.md +0 -125
@@ -1,1214 +0,0 @@
1
- # Alloy Models
2
-
3
- 1. [Overview](#overview)
4
- 2. [Alloy Collection and Model Objects](#alloy-collection-and-model-objects)
5
- 3. [Alloy Data Binding](#alloy-data-binding)
6
- 4. [Alloy Sync Adapters and Migrations](#alloy-sync-adapters-and-migrations)
7
- 5. [Backbone Objects without Alloy](#backbone-objects-without-alloy)
8
- 6. [Alloy Backbone Migration](#alloy-backbone-migration)
9
-
10
- ## Overview
11
-
12
- Alloy uses Backbone.js to provide support for its models and collections. Alloy also borrows the concepts of migrations and adapters from Rails for storage integration.
13
-
14
- For models, collections and sync adapters, these guides only provides information on how Alloy uses the Backbone.js functionality and some simple examples of using it.
15
-
16
- ## Alloy Collection and Model Objects
17
-
18
- ### Models
19
-
20
- In Alloy, models inherit from the [Backbone.Model](https://backbonejs.org/#Model-View-separation) class. They contain the interactive data and logic used to control and access it. Models are specified with JavaScript files, which provide a table schema, adapter configuration and logic to extend the Backbone.Model class. Models are automatically defined and available in the controller scope as the name of the JavaScript file.
21
-
22
- The JavaScript file exports a definition object comprised of three different objects. The first object, called `config`, defines the table schema and adapter information. The next two objects `extendModel` and `extendCollection` define functions to extend, override or implement the Backbone.Model and Backbone.Collection classes, respectively.
23
-
24
- **Example of the anatomy of a model file**
25
-
26
- ```
27
- exports.definition = {
28
- config : { // table schema and adapter information
29
- },
30
- extendModel(Model) {
31
- _.extend(Model.prototype, { // Extend, override or implement Backbone.Model
32
- });
33
-
34
- return Model;
35
- },
36
- extendCollection(Collection) {
37
- _.extend(Collection.prototype, { // Extend, override or implement Backbone.Collection
38
- });
39
-
40
- return Collection;
41
- }
42
- }
43
- ```
44
-
45
- To access a model locally in a controller, use the `Alloy.createModel` method. The first required parameter is the name of the JavaScript file minus the '.js' extension. The second optional parameter is the attributes for initializing the model object. For example:
46
-
47
- **Basic model usage**
48
-
49
- ```javascript
50
- const book = Alloy.createModel('book', {title:'Green Eggs and Ham', author:'Dr. Seuss'});
51
- const title = book.get('title');
52
- const author = book.get('author');
53
-
54
- // Label object in the view with id = 'label'
55
- $.label.text = title + ' by ' + author;
56
- ```
57
-
58
- The `book` model object is a Backbone object wrapped by Alloy, so it can be treated as a Backbone.Model object. You can use any Backbone Model or Events APIs with this object.
59
-
60
- You can also create a global singleton instance of a model, either in markup or in the controller, which may be accessed in all controllers. Use the `Alloy.Models.instance` method with the name of the model file minus the extension as the only parameter to create or access the singleton. For example:
61
-
62
- **Working with globally registered models**
63
-
64
- ```javascript
65
- // This will create a singleton if it has not been previously created,
66
- // or retrieves the singleton if it already exists.
67
- const book = Alloy.Models.instance('book');
68
- ```
69
-
70
- #### Configuration Object
71
-
72
- The `config` object is comprised of three different objects: `columns`, `defaults` and `adapter`.
73
-
74
- The `columns` object defines the table schema information. The key is the record name and the value is the data type. The following data types are accepted and mapped to the appropriate SQLite type: `string`, `varchar`, `int`, `tinyint`, `smallint`, `bigint`, `double`, `float`, `decimal`, `number`, `date`, `datetime` and `boolean`. By default, any unknown data type maps to the SQLite type `TEXT`. Alternatively, the SQLite sync adapter accepts the SQLite keywords.
75
-
76
- The optional `defaults` object defines the default values for a record if one or more record fields are left undefined upon creation. The key is the record name and the value is the default value.
77
-
78
- The adapter object defines how to access persistent storage. It contains two key-value pairs: `type` and `collection_name`. The `type` key identifies the sync adapter and the `collection_name` key identifies the name of the table in the database or a namespace.
79
-
80
- For example, suppose there is a model object called book (`book.js`) defined as:
81
-
82
- **book.js**
83
-
84
- ```javascript
85
- exports.definition = {
86
- config: {
87
- "columns": {
88
- "title": "String",
89
- "author": "String"
90
- },
91
- "defaults": {
92
- "title": "-",
93
- "author": "-"
94
- },
95
- "adapter": {
96
- "type": "sql",
97
- "collection_name": "books"
98
- }
99
- }
100
- }
101
- ```
102
-
103
- The code above describes a book object, which has two `string` (or `TEXT`) fields: `title` and `author`. If either field is left undefined, it will be assigned with the default value, a dash ("-"). The `sql` type configures Backbone to use the SQL adapter to sync with the SQLite engine on Android and iOS devices to access a table in the database called "books".
104
-
105
- You may add custom properties to the `config` object, which are available to the application as the model or collection's `config` property or can be processed by a custom sync adapter during application initialization.
106
-
107
- #### Extending the Backbone.Model Class
108
-
109
- The Backbone.Model class can be extended using the `extendModel` object, which implements the Backbone.Model `extend` method. This allows the Backbone.js code to be extended, overridden or implemented.
110
-
111
- For example, the `validate` method is left unimplemented by Backbone.js. The model JS file can implement `validate(attrs)`, where the parameter `attrs` are changed attributes in the model. In Backbone.js, if `validate` is implemented, it is called by the `set` and `save(attributes)` methods before changing the attributes and is also called by the `isValid` method. For the `save` method, validate is called if the `attributes` parameter is defined.
112
-
113
- In the example code `book.js` below, the JavaScript file implements the validate method, and adds a custom property and function.
114
-
115
- **Extending a model**
116
-
117
- ```javascript
118
- exports.definition = {
119
- config : { // table schema and adapter information
120
- },
121
-
122
- extendModel(Model) {
123
- _.extend(Model.prototype, {
124
- // Implement the validate method
125
- validate(attrs) {
126
- for (const key in attrs) {
127
- const value = attrs[key];
128
- if (key === "title") {
129
- if (value.length <= 0) {
130
- return "Error: No title!";
131
- }
132
- }
133
- if (key === "author") {
134
- if (value.length <= 0) {
135
- return "Error: No author!";
136
- }
137
- }
138
- }
139
- },
140
- // Extend Backbone.Model
141
- customProperty: 'book',
142
- customFunction() {
143
- Ti.API.info('I am a book model.');
144
- },
145
- });
146
-
147
- return Model;
148
- }
149
- }
150
- ```
151
-
152
- In the controller, to access the model, do:
153
-
154
- ```javascript
155
- const book = Alloy.createModel('book', {title:'Green Eggs and Ham', author:'Dr. Seuss'});
156
- // Since set or save(attribute) is not being called, we can call isValid to validate the model object
157
- if (book.isValid() && book.customProperty == "book") { // Save data to persistent storage
158
- book.save();
159
- }
160
- else {
161
- book.destroy();
162
- }
163
- ```
164
-
165
- ### Collections
166
-
167
- Collections are ordered sets of models and inherit from the Backbone.Collection class. Alloy Collections are automatically defined and available in the controller scope as the name of the model. To access a collection in the controller locally, use the `Alloy.createCollection` method with the name of the JavaScript file minus the '.js' extension as the required parameter. The second optional parameter can be an array of model objects for initialization. For example, the code below creates a collection using the previously defined model and reads data from persistent storage:
168
-
169
- **Creating collections**
170
-
171
- ```javascript
172
- const library = Alloy.createCollection('book');
173
- library.fetch(); // Grab data from persistent storage
174
- ```
175
-
176
- The `library` collection object is a Backbone object wrapped by Alloy, so it can be treated as a Backbone.Collection object. You can use any Backbone Collection or Events APIs with this object.
177
-
178
- You can also create a global singleton instance, either in markup or in the controller, which may be accessed in all controllers. Use the `Alloy.Collections.instance` method with the name of the model file minus the extension as the only parameter to create or access the singleton. For example:
179
-
180
- **Working with globally registered collections**
181
-
182
- ```javascript
183
- // This will create a singleton if it has not been previously created,
184
- // or retrieves the singleton if it already exists.
185
- const library = Alloy.Collections.instance('book');
186
- ```
187
-
188
- #### Extending the Backbone.Collection Class
189
-
190
- Like the Backbone.Model class, the Backbone.Collection class can be similarly extended in the model JavaScript file. For example, the `comparator` method is left unimplemented in Backbone.js. The code below sorts the library by book title:
191
-
192
- **Extending a collection**
193
-
194
- ```
195
- exports.definition = {
196
- config : { // table schema and adapter information
197
- },
198
- extendModel(Model) {
199
- _.extend(Model.prototype, { // Extend, override or implement Backbone.Model methods
200
- });
201
- return Model;
202
- },
203
- extendCollection(Collection) {
204
- _.extend(Collection.prototype, { // Implement the comparator method.
205
- comparator(book) {
206
- return book.get('title');
207
- }
208
- }); // end extend
209
-
210
- return Collection;
211
- }
212
- }
213
- ```
214
-
215
- #### Underscore.js Functionality
216
-
217
- Also, the Backbone.Collection class inherits some functionality from [Underscore.js](https://underscorejs.org/), which can help simplify iterative functions. For example, to add the title of each book object in the library collection to a table, you could use the `map` function to set the table:
218
-
219
- **Iterating over a collection with underscore**
220
-
221
- ```javascript
222
- const data = library.map(book => {
223
- // The book argument is an individual model object in the collection
224
- const title = book.get('title');
225
- const row = Ti.UI.createTableViewRow({"title":title});
226
- return row;
227
- });
228
- // TableView object in the view with id = 'table'
229
- $.table.setData(data);
230
- ```
231
-
232
- ### Event Handling
233
-
234
- When working with Alloy Models and Collections, use the Backbone.Events `on`, `off` and `trigger` methods. For example:
235
-
236
- **Using events with collections**
237
-
238
- ```javascript
239
- const library = Alloy.createCollection('book');
240
- function event_callback (context) {
241
- const output = context || 'change is bad.';
242
- Ti.API.info(output);
243
- };
244
- // Bind the callback to the change event of the collection.
245
- library.on('change', event_callback);
246
- // Trigger the change event and pass context to the handler.
247
- library.trigger('change', 'change is good.');
248
- // Passing no parameters to the off method unbinds all event callbacks to the object.
249
- library.off();
250
- // This trigger does not have a response.
251
- library.trigger('change');
252
- ```
253
-
254
- Alloy Model and Collection objects don't support the Titanium `addEventListener`, `removeEventListener` and `fireEvent` methods.
255
-
256
- If you are using Alloy's Model-View binding mechanism, the Backbone add, change, destroy, fetch, remove, and reset events are automatically bound to an internal callback to update the model data in the view. Be careful not to override or unbind these events.
257
-
258
- If you want to fire or listen to multiple events, Backbone.js uses spaces to delimit its events in the event string; therefore, do **NOT** name any custom events with spaces.
259
-
260
- ## Alloy Data Binding
261
-
262
- ### Introduction
263
-
264
- When data in the collection changes, you may want to update the view simultaneously to keep information synchronized. This concept is known as data binding. Both Alloy and Backbone provide some mechanisms to bind model data to a view.
265
-
266
- ### Alloy Binding
267
-
268
- In Alloy, collection data can be synchronized to a view object, or a single model can be bound to a view component. Alloy monitors the Backbone add, change, destroy, fetch, remove, and reset events to update the data in the view.
269
-
270
- #### Collection-View Binding
271
-
272
- To enable collection-view binding, create a global singleton or controller-specific collection using the [Collection tag](https://titaniumsdk.com/guide/Alloy_Framework/Alloy_Guide/Alloy_Views/Alloy_XML_Markup.html#collection-element) in the XML markup of the main view, then add the view object you want to bind data to. The following Titanium view objects support binding to a Collection:
273
-
274
- | View Object | Since Alloy version | Add data binding attributes to... | Repeater Object to map model attributes to view properties |
275
- | -------------- | ------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------ |
276
- | ButtonBar | 1.1 | `<Labels>` | `<Label/>` |
277
- | CoverFlowView | 1.1 | `<Images>` | `<Image/>` |
278
- | ListView | 1.2 | `<ListSection>` | `<ListItem/>` |
279
- | Map Module | 1.4 | `<Module module="ti.map" method="createView">` | None, model attributes will be used as params for createAnnotation() directly. |
280
- | Picker | 1.5 | `<PickerColumn>` or `<Column>` | `<PickerRow/>` or `<Row/>` |
281
- | ScrollableView | 1.1 | `<ScrollableView>` | `<View/>` May contain children view objects. |
282
- | TableView | 1.0 | `<TableView>` | `<TableViewRow/>` May contain children view objects. |
283
- | TabbedBar | 1.1 | `<Labels>` | `<Label/>` |
284
- | Toolbar | 1.1 | `<Items>` | `<Item/>` |
285
- | View | 1.0 | `<View>` | Any view object except a top-level container like a Window or TabGroup |
286
-
287
- You need to specify additional attributes in the markup, which are only specific to collection data binding. The only mandatory attribute is `dataCollection`, which specifies the collection singleton or instance to render. Note that you can only add these attributes to specific XML elements (refer to the table above).
288
-
289
- * `dataCollection`: specifies the collection singleton or instance to bind to the table. This is the name of the model file for singletons or the ID prefixed with the controller symbol ('$') for instances.
290
-
291
- * `dataTransform`: specifies an optional callback to use to format model attributes. The passed argument is a model and the return value is a modified model as a JSON object.
292
-
293
- * `dataFilter`: specifies an optional callback to use to filter data in the collection. The passed argument is a collection and the return value is an array of models.
294
-
295
- * `dataFunction`: set to an arbitrary identifier (name) for a function call. Use this identifier to call a function in the controller to manually update the view. This is not a declared function in the controller. This attribute creates an alias to access the underlying binding function, which is part of the Alloy data-view binding framework.
296
-
297
- Next, create a repeater object (refer to the table above) and place it inline with the view object with the `dataCollection` attribute, or place it in a separate view and use the `Require` tag to import it.
298
-
299
- To map model attributes, enclose the attribute with curly brackets or braces ('{' and '}'). You can map more than one attribute to a repeater object's property. For example, to assign the Label.text property to the model's title and author attributes, use this notation: `<Label text="{title} by {author}" />.` For more complex transformations, use the `dataTransform` callback to create a custom attribute.
300
-
301
- In the controller code of the repeater object, you can use the special variable `$model` to reference the current model being iterated over. This variable is present only in data bound controllers and is a reference to the currently bound model. For example, to get the title attribute of the current model, use `$model.title` to access it.
302
-
303
- > **⚠️ ⚠️ Warning**
304
- > **IMPORTANT:** When using Alloy's data binding in a view-controller, you **MUST** call the `$.destroy()` function when closing a controller to prevent potential memory leaks. The `destroy` function unbinds the callbacks created by Alloy when the collection-view syntax is used. For example:
305
- >
306
- > ```javascript
307
- > $.win.addEventListener("close", () => {
308
- > $.destroy();
309
- > });
310
- > ```
311
- >
312
- > For global singletons, to properly release them you should also remove event handlers with `off()` and set the reference to null:
313
- >
314
- > ```javascript
315
- > $.win.addEventListener("close", () => {
316
- > $.destroy();
317
- > Alloy.Collections.book.off();
318
- > Alloy.Collections.book = null;
319
- > });
320
- > ```
321
-
322
- #### Collection-View Binding Example
323
-
324
- The following example demonstrates how to add basic collection-view binding to an application. The example binds a collection of album models to a ScrollableView. In the ScrollableView, each model has its own view, which displays the album cover, title of the album and the artist. The `artist` and `title` attributes are bound to a Label object and the `cover` attribute is bound to an ImageView object.
325
-
326
- 1. Add the `<Collection>` tag as a child of the `<Alloy>` tag.
327
-
328
- **app/views/index.xml**
329
-
330
- ```xml
331
- <Alloy>
332
- <Collection src="album" />
333
- </Alloy>
334
- ```
335
-
336
- 2. Next, add the view object(s) you want to bind the data to. In this example, data will be bound to a ScrollableView object.
337
-
338
- **app/views/index.xml**
339
-
340
- ```xml
341
- <Alloy>
342
- <Collection src="album" />
343
- <Window backgroundColor="white" onClose="cleanup">
344
- <ScrollableView></ScrollableView>
345
- </Window>
346
- </Alloy>
347
- ```
348
-
349
- 3. Add the `dataCollection` attribute to the appropriate view object. Assign this attribute to the collection you want to use. For a ScrollableView object, add the attribute to the `<ScrollableView>` tag. The element to add the attribute to depends on which view object you want to bind data to.
350
-
351
- **app/views/index.xml**
352
-
353
- ```xml
354
- <Alloy>
355
- <Collection src="album" />
356
- <Window backgroundColor="white" onClose="cleanup">
357
- <ScrollableView dataCollection="album"></ScrollableView>
358
- </Window>
359
- </Alloy>
360
- ```
361
-
362
- 4. Next, create your repeater object and add model attributes. Enclose the model attributes with curly brackets or braces ('{' and '}'). For a ScrollableView, the repeater object can be a View object with additional children objects. The repeater object depends on which view object you are using.
363
-
364
- **app/views/index.xml**
365
-
366
- ```xml
367
- <Alloy>
368
- <Collection src="album"/>
369
- <Window backgroundColor="white" onClose="cleanup">
370
- <ScrollableView dataCollection="album">
371
- <View layout="vertical">
372
- <ImageView image="{cover}" />
373
- <Label text="{title} by {artist}" />
374
- </View>
375
- </ScrollableView>
376
- </Window>
377
- </Alloy>
378
- ```
379
-
380
- 5. In the controller, call the Collection's `fetch()` method to initialize the collection and sync any stored models to the view. Remember to call the `$.destroy()` method when you close the controller to prevent memory leaks.
381
-
382
- **app/controllers/index.js**
383
-
384
- ```javascript
385
- $.index.open();
386
- Alloy.Collections.album.fetch();
387
-
388
- function cleanup() {
389
- $.destroy();
390
- }
391
- ```
392
-
393
- The application is now setup for basic collection-view binding. When any new data is added to the collection, the ScrollableView will be updated with the new data.
394
-
395
- #### Model-View Binding
396
-
397
- To bind a single model to a component, create a global singleton or controller-specific model using the [Model tag](https://titaniumsdk.com/guide/Alloy_Framework/Alloy_Guide/Alloy_Views/Alloy_XML_Markup.html#model-element) in the XML markup of the main view and map the model attribute to the view component. To map the attribute to the view component, prefix the model name or id to the attribute, then enclose it with curly brackets or braces ('{' and '}').
398
-
399
- To do complex transformations on the model attributes, extend the model prototype with a `transform()` function. It should return the modified model as a JSON object.
400
-
401
- **app/models/album.js**
402
-
403
- ```javascript
404
- exports.definition = {
405
- config: {}, // model definition
406
- extendModel(Model) {
407
- _.extend(Model.prototype, {
408
- transform() {
409
- const transformed = this.toJSON();
410
- transformed.artist = transformed.artist.toUpperCase();
411
- return transformed;
412
- }
413
- });
414
- return Model;
415
- }
416
- };
417
- ```
418
-
419
- A global singleton instance is a single instance of a particular model that is available for use anywhere in your application. When using global instances, they will be in memory for the duration of your application unless you manually release them. The process of manually releasing them should include:
420
-
421
- * If any controllers are using data binding that relies on the global instance, they should call their own destroy() function: `$.destroy()`
422
- * Any other event handlers added to the global instance should be removed with the [off()](http://backbonejs.org/#Events-off) function
423
- * Set the reference of the model to null: `Alloy.Models.nameOfModel = null;`
424
-
425
- Note that you need to call the `$.destroy()` function when closing the controller to prevent potential memory leaks. The `destroy` function unbinds the callbacks created by Alloy when the model-view syntax is used.
426
-
427
- #### Model-View Binding Example
428
-
429
- The example below demonstrates how to bind a model to view components in the XML markup. Notice that each attribute is prefixed with the model's name and enclosed with braces.
430
-
431
- ```xml
432
- <Alloy>
433
- <Model src="settings"/>
434
- <Window backgroundColor="white" onClose="cleanup">
435
- <View layout="vertical">
436
- <Label text="Text Size" />
437
- <Slider value="{settings.textsize}" max="5" min="1"/>
438
- <Label text="Bold"/>
439
- <Switch value="{settings.bold}" />
440
- <Label text="Italics"/>
441
- <Switch value="{settings.italics}" />
442
- </View>
443
- </Window>
444
- </Alloy>
445
- ```
446
-
447
- #### Collection Example
448
-
449
- The example below demonstrates how to display all book models in the collection by the author Mark Twain. It also demonstrates how to use each of the data binding attributes.
450
-
451
- **app/views/index.xml**
452
-
453
- ```xml
454
- <Alloy>
455
- <Collection src="book" />
456
- <Window class="container">
457
- <TableView dataCollection="book"
458
- dataTransform="transformFunction"
459
- dataFilter="filterFunction"
460
- dataFunction="updateUI"
461
- onDragEnd="refreshTable">
462
- <!-- Also can use Require -->
463
- <TableViewRow title="{title}" />
464
- </TableView>
465
- </Window>
466
- </Alloy>
467
- ```
468
-
469
- **app/controllers/index.js**
470
-
471
- ```javascript
472
- $.index.open();
473
-
474
- // Encase the title attribute in square brackets
475
- function transformFunction(model) {
476
- // Need to convert the model to a JSON object
477
- const transform = model.toJSON();
478
- transform.title = '[' + transform.title + ']';
479
- // Example of creating a custom attribute, reference in the view using {custom}
480
- transform.custom = transform.title + " by " + transform.author;
481
- return transform;
482
- }
483
-
484
- // Show only book models by Mark Twain
485
- function filterFunction(collection) {
486
- return collection.where({author:'Mark Twain'});
487
- }
488
-
489
- function refreshTable(){
490
- // Trigger the binding function identified by the dataFunction attribute
491
- updateUI();
492
- }
493
-
494
- // Trigger the synchronization
495
- const library = Alloy.Collections.book;
496
- library.fetch();
497
-
498
- // Free model-view data binding resources when this view-controller closes
499
- $.index.addEventListener('close', () => {
500
- $.destroy();
501
- });
502
- ```
503
-
504
- As the collection is updated, the view reflects the changes made to the models. If you want to suppress an update, specify `{silent: true}` in the `options` parameters when calling Backbone methods to change model data.
505
-
506
- ### Collection vs Model Data Binding
507
-
508
- You can bind both a collection of models or an individual model. To bind a model attribute the opening curly bracket is first followed by the model name and then the attribute. To bind a collection you add the `dataCollection` attribute to the container using the collection name as value. The generated code will then loop over the collection and add the child elements to the container for each model.
509
-
510
- ```xml
511
- <Alloy>
512
- <Model src="currentCategory" />
513
- <Collection src="book" />
514
- <Window>
515
- <!-- model data binding -->
516
- <Label text="{currentCategory.name}" />
517
-
518
- <!-- collection data binding -->
519
- <ScrollView dataCollection="book">
520
- <Label text="{title}" />
521
- </ScrollView>
522
- </Window>
523
- </Alloy>
524
- ```
525
-
526
- ### Global Singleton vs Local Instance
527
-
528
- In the above code snippet, the model and collection are global singletons under `Alloy.Models.currentCategory` and `Alloy.Collections.book`. You can also use local instances for the current controller by adding `instance="true"` as attribute. You also need to assign them an ID to reference them in the XML and controller.
529
-
530
- ```xml
531
- <Alloy>
532
- <Model src="currentCategory" instance="true" id="c" />
533
- <Collection src="book" instance="true" id="b" />
534
- <Window>
535
- <!-- model data binding -->
536
- <Label text="{$.c.name}" />
537
-
538
- <!-- collection data binding -->
539
- <ScrollView dataCollection="$.b">
540
- <Label text="{title}" />
541
- </ScrollView>
542
- </Window>
543
- </Alloy>
544
- ```
545
-
546
- ### Simple vs Complex Data Binding
547
-
548
- It's important to understand the difference between simple and complex data binding as they were implemented in unique ways which results in different behaviour.
549
-
550
- Simple data binding involves one model attribute where complex data binding involves a combination of strings (including white space) and model attributes or even multiple model attributes:
551
-
552
- ```xml
553
- <Alloy>
554
- <Model src="book">
555
- <Window>
556
- <!-- simple -->
557
- <Label text="{book.title}" />
558
-
559
- <!-- complex -->
560
- <Label text="Title: {book.title}" />
561
- <Label text="{book.author.name} {book.author.email}" />
562
- </Window>
563
- </Alloy>
564
- ```
565
-
566
- ### Backbone Binding
567
-
568
- The application can monitor Backbone events to trigger updates to the view.
569
-
570
- For instance, the code below demonstrates how to update a table when a model object is added to a collection by monitoring the add event:
571
-
572
- ```javascript
573
- library.on('add', e => {
574
- // custom function to update the content on the view
575
- updateFooView(library);
576
- });
577
- ```
578
-
579
- Another method is to selectively monitor changes. For instance, the code below demonstrates how to update data if a title changes in the collection:
580
-
581
- ```javascript
582
- library.on('change:title', e => {
583
- // custom function to update the content on the view
584
- updateFooView(library);
585
- });
586
- ```
587
-
588
- > **⚠️ ⚠️ Warning**
589
- > This only works if the Backbone method fires the change event and does not enable `{silent: true}` as an option.
590
-
591
- If you want to suppress an update, specify `{silent: true}` in the `options` parameters when calling Backbone methods to change model data. The data-bound view will not be updated to reflect the changes.
592
-
593
- ### Bind Deep Object Properties
594
-
595
- You can bind deep object properties:
596
-
597
- ```xml
598
- <Alloy>
599
- <Model src="book" />
600
- <Label text="{book.author.name}" />
601
- </Alloy>
602
- ```
603
-
604
- Before, you needed to use a transformer to create a reference like `authorName`.
605
-
606
- Before CLI 7.1.0, the only way to set object properties (e.g. `font.fontFamily` for a Label) was to use TSS. You can use dot notation in XML:
607
-
608
- ```xml
609
- <Alloy>
610
- <Model src="book" />
611
- <Label font.fontFamily="Roboto">Hello</Label>
612
- </Alloy>
613
- ```
614
-
615
- ### Use Models and Properties with Special Characters
616
-
617
- You can bind models and properties that use names with special characters like dashes and spaces. Simply wrap the names in square brackets and quotes like you'd do in JavaScript:
618
-
619
- ```xml
620
- <Alloy>
621
- <Model src="my-model">
622
- <Label text="['my-model']['my-property']" />
623
- </Alloy>
624
- ```
625
-
626
- ### Bind Multiple Models to the Same View
627
-
628
- You have the ability to bind multiple models to the same view:
629
-
630
- ```xml
631
- <Alloy>
632
- <Model src="a" />
633
- <Model src="b" />
634
- <Label text="{a.hello} {b.world}" />
635
- </Alloy>
636
- ```
637
-
638
- ### Define Transformations in the Model
639
-
640
- Since Alloy 1.8.1, all types of data binding will generate the following logic to determine what object will be bound to the view:
641
-
642
- ```javascript
643
- let t;
644
- if (_.isFunction(<dataTransform>)) { // only for collection binding
645
- t = <dataTransform>(model);
646
- } else if (_.isFunction(model.transform)) {
647
- t = model.transform();
648
- } else {
649
- t = model.toJSON();
650
- }
651
- $.myLabel.text = t.author.name;
652
- ```
653
-
654
- You'd extend a model with a `transform()` method as such:
655
-
656
- ```javascript
657
- exports.definition = {
658
- // config
659
- extendModel(Model) {
660
- _.extend(Model.prototype, {
661
- transform() {
662
- const t = this.toJSON();
663
- t.titleCaps = t.title.toUpperCase();
664
- return t;
665
- }
666
- });
667
- return Model;
668
- }
669
- };
670
- ```
671
-
672
- > **⚠️ ⚠️ Warning**
673
- > The `transform` method must return **all** bound properties, not just the transformed ones. Until Alloy 1.8.1, simple collection data binding did not require this and automatically fell back to the model attributes.
674
-
675
- ### Tips and Tricks
676
-
677
- #### Lazy Transformation
678
-
679
- The advantage of defining transformations in the model is that you don't need to repeat them in every controller. A possible disadvantage is that everywhere you bind the model all transformations are computed where you might only need some.
680
-
681
- You can handle this using `Object.defineProperty()`. Its `get` callback will only be called when the transform key is actually requested:
682
-
683
- ```javascript
684
- const moment = require('alloy/moment');
685
-
686
- exports.definition = {
687
- extendModel(Model) {
688
- _.extend(Model.prototype, {
689
- transform() {
690
- const model = this;
691
- const t = this.toJSON();
692
-
693
- Object.defineProperty(t, 'dateFormatted', {
694
- get() {
695
- return moment(t.date).format('LLLL');
696
- }
697
- });
698
-
699
- return t;
700
- }
701
- });
702
- return Model;
703
- }
704
- };
705
- ```
706
-
707
- #### Populating a Model After Data Binding
708
-
709
- When Alloy compiles your views and controllers, the generated view code precedes your controller code. Any models you define for data binding in the XML will also be created at that point. Just like you call `fetch()` to populate the collection, you do the exact same thing for the model.
710
-
711
- **index.xml**
712
-
713
- ```xml
714
- <Alloy>
715
- <Model src="book" instance="true" id="current" />
716
- <Window>
717
- <Label text="{book.title}" />
718
- </Window>
719
- </Alloy>
720
- ```
721
-
722
- **index.js**
723
-
724
- ```javascript
725
- $.current.fetch({
726
- id: Ti.App.Properties.getString('currentBook')
727
- });
728
-
729
- $.index.open();
730
- ```
731
-
732
- > **⚠️ ⚠️ Warning**
733
- > With the release of CLI 7.1.0, values passed in at creation of a view can be used as values in TSS and XML. For example, if the **foo** property was passed in at creation it can be used on a label:
734
- >
735
- > ```xml
736
- > <Alloy>
737
- > <Label text="$.args.foo" />
738
- > </Alloy>
739
- > ```
740
-
741
- ## Alloy Sync Adapters and Migrations
742
-
743
- ### Sync Adapters
744
-
745
- In Alloy, a sync adapter allows you to store and load your models to a persistent storage device, such as an on-device database or remote server. Alloy relies on the Backbone API to sync model data to persistent storage.
746
-
747
- #### Backbone Sync
748
-
749
- Backbone syncs your models to persistent storage devices based on the implementation of the [Backbone.sync method](https://titaniumsdk.com/guide/Alloy_Framework/Alloy_Guide/Alloy_Models/Alloy_Sync_Adapters_and_Migrations.html). Since Backbone's primary use is for web applications, by default, the Backbone.sync method executes RESTful JSON requests to a URL specified by the Model.urlRoot or Collection.url attribute, when these classes are created.
750
-
751
- Models are accessed from persistent storage based on the `id` attribute. To override this, set the `idAttribute` property of the model. The `cid` (client ID) is a special property of models that is automatically assigned when they are first created. Client IDs are useful when the model has not yet been saved to the server and does not have its real `id` yet.
752
-
753
- The sync method depends on calls to other Backbone methods as described in the table below.
754
-
755
- | **Backbone Method** | **Sync CRUD Method** | **Equivalent HTTP Method** | **Equivalent SQL Method** |
756
- | ---------------------------------------------------------------- | -------------------- | -------------------------- | ------------------------- |
757
- | Collection.fetch | read | GET | SELECT |
758
- | Collection.create (id == null) or Collection.create (id != null) | create or update | POST or PUT | INSERT or UPDATE |
759
- | Model.fetch | read | GET | SELECT |
760
- | Model.save (id == null) or Model.save (id != null) | create or update | POST or PUT | INSERT or UPDATE |
761
- | Model.destroy | delete | DELETE | DELETE |
762
-
763
- #### Ready-Made Sync Adapters
764
-
765
- Alloy provides a few ready-made sync adapters. In the 'adapter' object, set the 'type' to use one of the following:
766
-
767
- * `sql` for the SQLite database on the Android and iOS platform.
768
- * `properties` for storing data locally in the Titanium SDK context. You do not need to define the `columns` object in the `config` object. If defined, the object is ignored.
769
- * `localStorage` for HTML5 localStorage on the Mobile Web platform. Deprecated since Alloy 1.5.0. Use the `properties` adapter instead.
770
-
771
- These adapters are part of Alloy and are copied to the `Resources/alloy/sync` folder during compilation. These sync adapters assign the `id` attribute of the models, which means if you assign an ID when creating a model, it is overridden by any sync operations.
772
-
773
- ##### SQLite Sync Adapter Features
774
-
775
- The `sql` sync adapter has a few extra features:
776
-
777
- **Fetch method accepts SQL Query**
778
-
779
- The Backbone.Collection.fetch method supports SQL queries as a parameter. Use `query` as the key in the dictionary object to create a simple query or query with a prepared statement.
780
-
781
- ```javascript
782
- const library = Alloy.createCollection('book');
783
- const table = library.config.adapter.collection_name;
784
- // use a simple query
785
- library.fetch({query:'SELECT * from ' + table + ' where author="' + searchAuthor + '"'});
786
- // or a prepared statement
787
- library.fetch({query: { statement: 'SELECT * from ' + table + ' where author = ?', params: [searchAuthor] }});
788
- ```
789
-
790
- **Fetch method accepts ID attribute**
791
-
792
- Since Alloy 1.3.0, to fetch a single model using its ID, pass a dictionary with one key-value pair, where `id` is the key and the model's ID as the value to retrieve that model, to the `fetch` method instead of using a SQL query. For example:
793
-
794
- ```
795
- myModel.fetch({id: 123});
796
- // is equivalent to
797
- myModel.fetch({query: 'select * from ... where id = ' + 123 });
798
- ```
799
-
800
- **Columns accept SQLite keywords**
801
-
802
- The columns values accept SQLite keywords, such as AUTOINCREMENT and PRIMARY KEY. For example:
803
-
804
- **app/models/book.js**
805
-
806
- ```javascript
807
- exports.definition = {
808
- config: {
809
- "columns": {
810
- "title": "TEXT",
811
- "author": "TEXT",
812
- "book_id": "INTEGER PRIMARY KEY AUTOINCREMENT"
813
- },
814
- "adapter": {
815
- "type": "sql",
816
- "collection_name": "books",
817
- "idAttribute": "book_id"
818
- }
819
- }
820
- }
821
- ```
822
-
823
- **Specify columns property as primary ID**
824
-
825
- Define the `idAttribute` key-value pair in the `config.adapter` object to use a `config.columns` key as the primary ID for the SQLite table. If this key is not set, Alloy creates the `alloy_id` column in the table and generates a default GUID as the model ID.
826
-
827
- **Specify a migration to use**
828
-
829
- Define the `migration` key-value pair in the `config.adapter` object to specify the database version to use. The value of this key is the datetime code of the migration file. Alloy upgrades or rolls back the database based on this value. If left undefined, Alloy upgrades the database based on the newest migration file.
830
-
831
- **Specify a database to use**
832
-
833
- Define the `db_name` key-value pair in the `config.adapter` object to specify the name of the database to use. If left undefined, Alloy uses the default database `_alloy_`.
834
-
835
- **Specify a database file to preload**
836
-
837
- Define the `db_file` key-value pair in the `config.adapter` object to specify the database file ('myfile.sqlite') to preload. Place this file in the `app/assets` directory of your Alloy project. Alloy creates a database using the name of the database file minus the file extension if one does not exist.
838
-
839
- ### Custom Sync Adapters
840
-
841
- To create a custom sync adapter, create a JavaScript file in either `app/assets/alloy/sync` or `app/lib/alloy/sync`. During compilation, this file is copied to the `Resources/alloy/sync` folder. In the `config` object of the model file, set the `type` in the `adapter` object to the name of the JavaScript file minus the '.js' extension.
842
-
843
- The sync adapter exports three functions:
844
-
845
- * `module.exports.beforeModelCreate` (optional) - executes code before creating the Backbone.Model class. First passed parameter is the `config` object from the model file. Second passed parameter is the name of the Alloy Model file. Returns a `config` object.
846
-
847
- * `module.exports.afterModelCreate` (optional) - execute code after creating the Backbone.Model class. First passed parameter is the newly created Backbone.Model class. Second passed parameter is the name of the Alloy Model file.
848
-
849
- * `module.exports.sync` - implement the Backbone.sync method.
850
-
851
- ### Migrations
852
-
853
- A migration is a description of incremental changes to a database, which takes your database from version 1 to version X, with a migration file for each step in the evolution of your database schema. This is helpful to keep different versions of a database in sync. For example, when version 7 of your application is deployed, migrations can successfully update the database from versions 1 through 6. Currently, migrations are only used with the `sql` sync adapter.
854
-
855
- The `migration.up` function upgrades the database from the previous version, while the `migration.down` function rolls back the changes to the previous version.
856
-
857
- In Alloy, migrations are defined by JavaScript files located in the `app/migrations` folder of the project. The file should be named the same as the model JavaScript file prefixed with 'YYYYMMDDHHmmss_' (datetime code followed by an underscore), for example, `20120610049877_book.js`. Alloy applies the migrations from oldest to newest, according to the datetime code at the beginning of the file name.
858
-
859
- The migration file contains two functions that need to be implemented: `migration.up(migrator)` and `migration.down(migrator)`, where `migrator` is a special migration object that provides references to the database and table as well as some convenient functions for table operations:
860
-
861
- | Key | Description |
862
- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
863
- | `db` | Handle to a `Ti.Database` instance. Use this handle to execute SQL calls using `db.execute`. DO NOT CLOSE THIS HANDLE OR OPEN A SECOND INSTANCE OF THE DATABASE. |
864
- | `dbname` | Name of the database. |
865
- | `table` | Name of the table. Same as value of the `config.adapter.collection_name` key. |
866
- | `idAttribute` | Name of the columns attribute to use as the primary key. |
867
- | `createTable` | Function to create a table. Required parameter is the `columns` object. |
868
- | `dropTable` | Function to drop the current table from the database. |
869
- | `insertRow` | Function to insert data into the table. Useful for preloading data. |
870
- | `deleteRow` | Function to delete data from the table. |
871
-
872
- For example, the migration file below is the initial version of the database that preloads some data in the table.
873
-
874
- **app/migrations/20120610049877_book.js**
875
-
876
- ```javascript
877
- const preload_data = [
878
- {title: 'To Kill a Mockingbird', author:'Harper Lee'},
879
- {title: 'The Catcher in the Rye', author:'J. D. Salinger'},
880
- {title: 'Of Mice and Men', author:'John Steinbeck'},
881
- {title: 'Lord of the Flies', author:'William Golding'},
882
- {title: 'The Great Gatsby', author:'F. Scott Fitzgerald'},
883
- {title: 'Animal Farm', author:'George Orwell'}
884
- ];
885
-
886
- migration.up = migrator => {
887
- migrator.createTable({
888
- "columns":
889
- {
890
- "book": "TEXT",
891
- "author": "TEXT"
892
- }
893
- });
894
- for (let i = 0; i < preload_data.length; i++) {
895
- migrator.insertRow(preload_data[i]);
896
- }
897
- };
898
-
899
- migration.down = migrator => {
900
- migrator.dropTable();
901
- };
902
- ```
903
-
904
- #### Migration Rollback Example
905
-
906
- Suppose later, you want to include some additional information for your books, such as an ISBN. The below migration file upgrades or rolls back the changes. Since SQLite does not support the DROP COLUMN operation, the migration needs to create a temporary table to hold the data, drop the new database, create the old database, then copy the data back. Note: if `idAttribute` is not specified, Alloy creates the `alloy_id` column and this column needs to be copied over as part of the migration.
907
-
908
- **app/migrations/20130118069778_book.js**
909
-
910
- ```javascript
911
- migration.up = migrator => {
912
- migrator.db.execute('ALTER TABLE ' + migrator.table + ' ADD COLUMN isbn INT;');
913
- };
914
-
915
- migration.down = migrator => {
916
- const db = migrator.db;
917
- const table = migrator.table;
918
- db.execute('CREATE TEMPORARY TABLE book_backup(title,author,alloy_id);')
919
- db.execute('INSERT INTO book_backup SELECT title,author,alloy_id FROM ' + table + ';');
920
- migrator.dropTable();
921
- migrator.createTable({
922
- columns: {
923
- title:"TEXT",
924
- author:"TEXT",
925
- },
926
- });
927
- db.execute('INSERT INTO ' + table + ' SELECT title,author,alloy_id FROM book_backup;');
928
- db.execute('DROP TABLE book_backup;');
929
- };
930
- ```
931
-
932
- ## Backbone Objects without Alloy
933
-
934
- You can use plain Backbone Collection and Model objects in place of the Alloy versions. This does not require any special Alloy or Titanium code. Use the Backbone API to create and control Backbone objects instead of using the `createCollection` and `createModel` methods. Backbone models also do not require a model configuration file.
935
-
936
- **app/controllers/index.js**
937
-
938
- ```javascript
939
- // Initialize a collection class and implement the comparator method for sorting
940
- const collection = Backbone.Collection.extend({
941
- comparator(model) {
942
- return model.get('title');
943
- }
944
- });
945
-
946
- // Create a new collection
947
- const library = new collection([
948
- {title: 'To Kill a Mockingbird', author:'Harper Lee'},
949
- {title: 'The Catcher in the Rye', author:'J. D. Salinger'},
950
- {title: 'Of Mice and Men', author:'John Steinbeck'},
951
- {title: 'Lord of the Flies', author:'William Golding'},
952
- {title: 'The Great Gatsby', author:'F. Scott Fitzgerald'},
953
- {title: 'Tom Sawyer', author:'Mark Twain'},
954
- {title: 'Animal Farm', author:'George Orwell'}
955
- ]);
956
-
957
- // Initialize a model class
958
- const modelClass = Backbone.Model.extend();
959
-
960
- // Create a new model and add it to the collection
961
- const book = new modelClass({title:'Bossypants', author:'Tina Fey'});
962
- library.add(book);
963
-
964
- // Remove the very first model from the collection
965
- const model = library.at(0);
966
- library.remove(model);
967
- ```
968
-
969
- These Backbone objects cannot persist to external storage without implementing the Backbone.sync method, so if you make calls to Collection.fetch, Collection.create, Model.fetch, Model.save and Model.destroy, the application throws an error.
970
-
971
- ### Using Backbone Objects with Alloy Data Binding
972
-
973
- You can use Alloy's Model-View binding mechanism to keep the local Backbone Models and Collections in sync with an Alloy view-controller. Follow the same directions for data binding except instead of using the `Model` or `Collections` XML tag, you need to first initialize your model or collection in the alloy.js initializer file and add it to the `Alloy.Models` or `Alloy.Collections` namespace.
974
-
975
- **app/alloy.js**
976
-
977
- ```javascript
978
- // Initialize a collection class and implement the comparator method for sorting
979
- const collection = Backbone.Collection.extend({
980
- comparator(model) {
981
- return model.get('title');
982
- }
983
- });
984
-
985
- // Create a new collection
986
- const library = new collection([
987
- {title: 'To Kill a Mockingbird', author:'Harper Lee'},
988
- {title: 'The Catcher in the Rye', author:'J. D. Salinger'},
989
- {title: 'Of Mice and Men', author:'John Steinbeck'},
990
- {title: 'Lord of the Flies', author:'William Golding'},
991
- {title: 'The Great Gatsby', author:'F. Scott Fitzgerald'},
992
- {title: 'Tom Sawyer', author:'Mark Twain'},
993
- {title: 'Animal Farm', author:'George Orwell'}
994
- ]);
995
-
996
- // Add the collection to the global scope
997
- Alloy.Collections.book = library;
998
- ```
999
-
1000
- **app/views/index.xml**
1001
-
1002
- ```xml
1003
- <!-- Markup the view the same except there is no Collection tag -->
1004
- <Alloy>
1005
- <Window class="container">
1006
- <TableView dataCollection="book" dataTransform="transformFunction" dataFilter="filterFunction">
1007
- <TableViewRow title="{title}" />
1008
- </TableView>
1009
- </Window>
1010
- </Alloy>
1011
- ```
1012
-
1013
- **app/controllers/index.js**
1014
-
1015
- ```javascript
1016
- $.index.open();
1017
-
1018
- function transformFunction(model) {
1019
- const transform = model.toJSON();
1020
- transform.title = '[' + transform.title + ']';
1021
- transform.custom = transform.title + " by " + transform.author;
1022
- return transform;
1023
- }
1024
-
1025
- function filterFunction(collection) {
1026
- return collection.where({author:'Mark Twain'});
1027
- }
1028
-
1029
- // Get a reference to the library
1030
- const library = Alloy.Collections.book;
1031
-
1032
- // Trigger the update using the 'change' event instead of the fetch method
1033
- library.trigger('change');
1034
-
1035
- // Initialize a model class
1036
- const modelClass = Backbone.Model.extend();
1037
-
1038
- // Create a new model and add it to the collection
1039
- const book = new modelClass({title:'Bossypants', author:'Tina Fey'});
1040
- library.add(book);
1041
-
1042
- // Remove the very first model from the collection
1043
- const model = library.at(0);
1044
- library.remove(model);
1045
-
1046
- // Do not forget to call destroy to unbind the event handlers created by Alloy
1047
- $.index.addEventListener('close', () => {
1048
- $.destroy();
1049
- });
1050
- ```
1051
-
1052
- ## Alloy Backbone Migration
1053
-
1054
- ### Overview
1055
-
1056
- Alloy 1.6.0 introduces support for Backbone 1.1.2. Currently, Alloy uses Backbone 0.9.2 to support its Model and Collection objects. This guide covers the changes from Backbone 0.9.2 to 1.1.2 and the modifications you may need to update your application. Note that only changes to the Backbone Collection, Event and Model APIs are discussed in this document.
1057
-
1058
- Due to breaking changes from Backbone 0.9.2 to 1.1.2, Alloy still uses Backbone 0.9.2 as its default Model and Collection implementation. You will need to update the configuration file to use the newer Backbone library.
1059
-
1060
- Alloy 1.10.12 adds support for Backbone 1.3.3. However, due to breaking changes in Backbone, 0.9.2 will remain the default version.
1061
-
1062
- Supported versions of Backbone for Alloy 1.10.12 are 0.9.2, 1.1.2, 1.3.3.
1063
-
1064
- ### Setup
1065
-
1066
- To use Backbone 1.1.2 to support Alloy Model and Collections objects, open the project's `./app/config.json` file and add the `backbone` key to the to the file with the value set to `1.1.2` (or `1.3.3`). You may also set this value to `0.9.2` to force support of Backbone 0.9.2.
1067
-
1068
- **app/config.json**
1069
-
1070
- ```json
1071
- {
1072
- "global": {},
1073
- "env:development": {},
1074
- "env:test": {},
1075
- "env:production": {},
1076
- "os:android": {},
1077
- "os:blackberry": {},
1078
- "os:ios": {},
1079
- "os:mobileweb": {},
1080
- "dependencies": {},
1081
- "backbone": "1.1.2"
1082
- }
1083
- ```
1084
-
1085
- ### Summary of Changes
1086
-
1087
- #### Collection APIs
1088
-
1089
- **Fetch Method Behavior Change**: Backbone Collection objects no longer emit the `reset` event after a `fetch()` call, which means data-bound views may not update automatically. **This could break existing apps.** To use old functionality, pass `{reset: true}` when calling `fetch()` or extend the Collection class:
1090
-
1091
- ```javascript
1092
- exports.definition = {
1093
- config: {
1094
- // Model configuration
1095
- },
1096
- extendModel(Model) {
1097
- _.extend(Model.prototype, {
1098
- // extended functions and properties go here
1099
- });
1100
- return Model;
1101
- },
1102
- extendCollection(Collection) {
1103
- _.extend(Collection.prototype, {
1104
- // For Backbone v1.1.2, uncomment the following to override the
1105
- // fetch method to account for a breaking change in Backbone.
1106
- /*
1107
- fetch(options) {
1108
- options = options ? _.clone(options) : {};
1109
- options.reset = true;
1110
- return Backbone.Collection.prototype.fetch.call(this, options);
1111
- }
1112
- */
1113
- });
1114
- return Collection;
1115
- }
1116
- };
1117
- ```
1118
-
1119
- **New Set Method**: To smartly update the contents of a Collection (adding new models, removing missing ones, and merging those already present), call `set()`.
1120
-
1121
- **Return Value for Methods**: The return values of Collection's `add()`, `push()`, `remove()`, `reset()` and `shift()` methods return the changed model or list of models, instead of `this`.
1122
-
1123
- **Add Method**: When invoking `add()` on a collection, passing `{merge: true}` will now cause duplicate models to have their attributes merged in to the existing models. To improve performance, `options.index` will no longer be set in the `add` event callback — use `collection.indexOf(model)` instead.
1124
-
1125
- #### Event APIs
1126
-
1127
- * All `invalid` events now pass consistent arguments. First the model in question, then the `error` object, then `options`.
1128
- * `Collection.sort()` now triggers a `sort` event, instead of a `reset` event.
1129
- * Both `sync` and `error` events within `Backbone.sync()` are now triggered regardless of the existence of success or error callbacks.
1130
- * While listening to a `reset` event, the list of previous models is now available in `options.previousModels`.
1131
- * The new Event methods `listenTo` and `stopListening` are meant for Backbone View objects. These APIs will not work with an Alloy application.
1132
-
1133
- #### Model APIs
1134
-
1135
- **Validation**: Model validation is now only enforced with the `save()` method. Previously, models were also validated with the `set()` method. To force validation when the `set()` method is called, pass `{validate: true}` to the method or extend the Model class. Also, validation now occurs even during 'silent' changes (passing `{silent: true}` to methods). Previously, it would not. Failed validations return the `invalid` event. Previously, a failed model validation would return the `error` event.
1136
-
1137
- > **⚠️ ⚠️ Warning**
1138
- > To validate Model objects, implement the `validate()` method in the `extendModel` key of the model configuration file.
1139
-
1140
- **Parse Method**: All `parse` methods now run after a `fetch`. You cannot change the `id` of a model during `parse`. The `parse` method receives `options` as a second parameter.
1141
-
1142
- **Other Changes**:
1143
-
1144
- * Calling `destroy()` on a Model will now return `false` if the model's `isNew` is set to `true`.
1145
- * `Model.set()` no longer accepts another model as an argument.
1146
- * `url` and `urlRoot` properties may now be passed as options when instantiating a new Model.
1147
- * If you want to maintain current models in a collection when using `fetch` the property has changed from `{add:true}` to `{remove:false}`.
1148
-
1149
- ### Parse Method
1150
-
1151
- After fetching a model or a collection, all defined parse methods will now be run. So fetching a collection and getting back new models could cause both the collection to parse the list, and then each model to be parsed in turn, if you have both methods defined. By default, the parse method is a no-op function that directly passes the JSON response object.
1152
-
1153
- You are no longer permitted to change the `id` of your model during `parse()`. Use `idAttribute` instead.
1154
-
1155
- The parse function now receives the `options` dictionary as its second parameter. Previously, it would only be passed a raw `response` object.
1156
-
1157
- ### Silent Option
1158
-
1159
- Passing `{silent:true}` to methods now suppresses the `change:attr` events, thus a data-bound view will not be updated to reflect the changes. The sql sync adapter passed this option by default. It has been updated to no longer pass that option when Backbone 1.1.2 is used (still passed with 0.9.2).
1160
-
1161
- If you want the new behavior where `change` events are suppressed, you will need to pass this option or extend the Model or Collection class. The following sample code extends the Model `set()` method by forcing the silent option to true:
1162
-
1163
- ```javascript
1164
- exports.definition = {
1165
- config: {
1166
- // Model configuration
1167
- },
1168
- extendModel(Model) {
1169
- _.extend(Model.prototype, {
1170
- // Forces silent true option when the model is updated
1171
- set(attributes, options) {
1172
- options = options ? _.clone(options) : {};
1173
- options.silent = true;
1174
- return Backbone.Model.prototype.set.call(this, attributes, options);
1175
- }
1176
- });
1177
- return Model;
1178
- },
1179
- extendCollection(Collection) {
1180
- _.extend(Collection.prototype, {
1181
- // extended functions and properties go here
1182
- });
1183
- return Collection;
1184
- }
1185
- };
1186
- ```
1187
-
1188
- ### API Changes
1189
-
1190
- #### New APIs
1191
-
1192
- The following APIs have been added between Backbone 1.1.2 and 0.9.2.
1193
-
1194
- | API | Type | Notes |
1195
- | ----------------------------- | ------ | ------------------------------------------------------------------------ |
1196
- | Backbone.request | event | Fired whenever a request begins to be made to the server. |
1197
- | Backbone.Collection.findWhere | method | Same as `where()` but only returns the first result. |
1198
- | Backbone.Collection.set | method | Performs a "smart" update of the collection. |
1199
- | Backbone.Event.once | method | Same as `on()` except after the event is fired, the callback is removed. |
1200
- | Backbone.Model.invert | method | Returns a copy of the object where keys and values are switched. |
1201
- | Backbone.Model.keys | method | Returns an array of the object's keys. |
1202
- | Backbone.Model.omit | method | Returns a copy of an object without the specified keys. |
1203
- | Backbone.Model.pairs | method | Returns an array of `[key, value]` pairs. |
1204
- | Backbone.Model.pick | method | Returns a copy of an object with the specified keys. |
1205
- | Backbone.Model.values | method | Returns an array of the object's property values. |
1206
-
1207
- #### Removed APIs
1208
-
1209
- The following APIs have been removed between Backbone 1.1.2 and 0.9.2.
1210
-
1211
- | API | Type | Notes |
1212
- | ---------------------------- | ------ | ------------------------------------------- |
1213
- | Backbone.Collection.getByCid | method | Pass the CID to the `get()` method instead. |
1214
- | Backbone.Model.change | method | |