Repository navigation
Expand file tree
/
Copy pathbindable.ts
More file actions
634 lines (559 loc) · 24.6 KB
/
Copy pathbindable.ts
File metadata and controls
634 lines (559 loc) · 24.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
import observable = require("data/observable");
import definition = require("ui/core/bindable");
import dependencyObservable = require("ui/core/dependency-observable");
import weakEvents = require("ui/core/weak-event-listener");
import types = require("utils/types");
import trace = require("trace");
import bindingBuilder = require("../builder/binding-builder");
import viewModule = require("ui/core/view");
import * as applicationModule from "application";
import * as polymerExpressionsModule from "js-libs/polymer-expressions";
import * as specialPropertiesModule from "ui/builder/special-properties";
import * as utils from "utils/utils";
//late import
var application: typeof applicationModule;
function ensureApplication() {
if (!application) {
application = require("application");
}
}
var expressions: typeof polymerExpressionsModule;
function ensureExpressions() {
if (!expressions) {
expressions = require("js-libs/polymer-expressions");
}
}
var specialProperties: typeof specialPropertiesModule;
function ensureSpecialProperties() {
if (!specialProperties) {
specialProperties = require("ui/builder/special-properties");
}
}
var bindingContextProperty = new dependencyObservable.Property(
"bindingContext",
"Bindable",
new dependencyObservable.PropertyMetadata(undefined, dependencyObservable.PropertyMetadataSettings.Inheritable, onBindingContextChanged)
);
function onBindingContextChanged(data: dependencyObservable.PropertyChangeData) {
var bindable = <Bindable>data.object;
bindable._onBindingContextChanged(data.oldValue, data.newValue);
}
var contextKey = "context";
// this regex is used to get parameters inside [] for example:
// from $parents['ListView'] will return 'ListView'
// from $parents[1] will return 1
var paramsRegex = /\[\s*(['"])*(\w*)\1\s*\]/;
var bc = bindingBuilder.bindingConstants;
export class Bindable extends dependencyObservable.DependencyObservable implements definition.Bindable {
public static bindingContextProperty = bindingContextProperty;
// TODO: Implement with WeakRef to prevent memory leaks.
private _bindings: Object;
private get bindings(): Object {
if (!this._bindings) {
this._bindings = {};
}
return this._bindings;
}
get bindingContext(): Object {
return this._getValue(Bindable.bindingContextProperty);
}
set bindingContext(value: Object) {
this._setValue(Bindable.bindingContextProperty, value);
}
public bind(options: definition.BindingOptions, source?: Object) {
var binding: Binding = this.bindings[options.targetProperty];
if (binding) {
binding.unbind();
}
binding = new Binding(this, options);
this.bindings[options.targetProperty] = binding;
var bindingSource = source;
if (!bindingSource) {
bindingSource = this.bindingContext;
binding.sourceIsBindingContext = true;
}
if (!types.isNullOrUndefined(bindingSource)) {
binding.bind(bindingSource);
}
}
public unbind(property: string) {
var binding: Binding = this.bindings[property];
if (binding) {
binding.unbind();
delete this.bindings[property];
}
}
public _updateTwoWayBinding(propertyName: string, value: any) {
var binding: Binding = this.bindings[propertyName];
if (binding) {
binding.updateTwoWay(value);
}
}
public _setCore(data: observable.PropertyChangeData) {
super._setCore(data);
this._updateTwoWayBinding(data.propertyName, data.value);
}
public _onPropertyChanged(property: dependencyObservable.Property, oldValue: any, newValue: any) {
trace.write(`${this}._onPropertyChanged(${property.name}, ${oldValue}, ${newValue})`, trace.categories.Binding);
super._onPropertyChanged(property, oldValue, newValue);
if (this instanceof viewModule.View) {
if (property.metadata.inheritable && (<viewModule.View>(<any>this))._isInheritedChange() === true) {
return;
}
}
var binding = this.bindings[property.name];
if (binding && !binding.updating) {
if (binding.options.twoWay) {
trace.write(`${this}._updateTwoWayBinding(${property.name}, ${newValue});` + property.name, trace.categories.Binding);
this._updateTwoWayBinding(property.name, newValue);
}
else {
trace.write(`${this}.unbind(${property.name});`, trace.categories.Binding);
this.unbind(property.name);
}
}
}
public _onBindingContextChanged(oldValue: any, newValue: any) {
var binding: Binding;
for (var p in this.bindings) {
binding = this.bindings[p];
if (binding.updating || !binding.sourceIsBindingContext) {
continue;
}
trace.write(`Binding ${binding.target.get()}.${binding.options.targetProperty} to new context ${newValue}`, trace.categories.Binding);
binding.unbind();
if (!types.isNullOrUndefined(newValue)) {
binding.bind(newValue);
}
}
}
}
export class Binding {
options: definition.BindingOptions;
updating = false;
sourceIsBindingContext: boolean;
source: WeakRef<Object>;
target: WeakRef<Bindable>;
public loadedHandlerVisualTreeBinding(args) {
var targetInstance = args.object;
targetInstance.off(viewModule.View.loadedEvent, this.loadedHandlerVisualTreeBinding, this);
this.unbind();
if (!types.isNullOrUndefined(targetInstance.bindingContext)) {
this.bind(targetInstance.bindingContext);
}
};
private propertyChangeListeners = {};
private sourceOptions: { instance: WeakRef<any>; property: any };
private targetOptions: { instance: WeakRef<any>; property: any };
private sourcePropertiesArray: Array<string>;
constructor(target: Bindable, options: definition.BindingOptions) {
this.target = new WeakRef(target);
this.options = options;
}
public bind(obj: Object) {
if (types.isNullOrUndefined(obj)) {
throw new Error("Expected valid object reference as a source in the Binding.bind method.");
}
/* tslint:disable */
if (typeof (obj) === "number") {
obj = new Number(obj);
}
if (typeof (obj) === "boolean") {
obj = new Boolean(obj);
}
if (typeof (obj) === "string") {
obj = new String(obj);
}
/* tslint:enable */
this.source = new WeakRef(obj);
this.updateTarget(this.getSourcePropertyValue());
if (!this.sourceOptions) {
this.sourceOptions = this.resolveOptions(this.source, this.getSourceProperties());
}
this.addPropertyChangeListeners(this.source, this.getSourceProperties());
}
private getSourceProperties(): Array<string> {
if (!this.sourcePropertiesArray) {
this.sourcePropertiesArray = Binding.getProperties(this.options.sourceProperty);
}
return this.sourcePropertiesArray;
}
private static getProperties(property: string): Array<string> {
var result: Array<string>;
if (property) {
// first replace all '$parents[..]' with a safe string
// second removes all ] since they are not important for property access and not needed
// then split properties either on '.' or '['
var parentsMatches = property.match(bindingBuilder.parentsRegex);
result = property.replace(bindingBuilder.parentsRegex, "parentsMatch")
.replace(/\]/g, "")
.split(/\.|\[/);
var i;
var resultLength = result.length;
var parentsMatchesCounter = 0;
for (i = 0; i < resultLength; i++) {
if (result[i] === "parentsMatch") {
result[i] = parentsMatches[parentsMatchesCounter];
parentsMatchesCounter++;
}
}
return result;
}
else {
return [];
}
}
private resolveObjectsAndProperties(source: Object, propsArray: Array<string>) {
var result = [];
var i;
var propsArrayLength = propsArray.length;
var currentObject = source;
var objProp = "";
var currentObjectChanged = false;
for (i = 0; i < propsArrayLength; i++) {
objProp = propsArray[i];
if (objProp === bc.bindingValueKey) {
currentObjectChanged = true;
}
if (objProp === bc.parentValueKey || objProp.indexOf(bc.parentsValueKey) === 0) {
var parentView = this.getParentView(this.target.get(), objProp).view;
if (parentView) {
currentObject = parentView.bindingContext;
} else {
var targetInstance = this.target.get();
targetInstance.off(viewModule.View.loadedEvent, this.loadedHandlerVisualTreeBinding, this);
targetInstance.on(viewModule.View.loadedEvent, this.loadedHandlerVisualTreeBinding, this);
}
currentObjectChanged = true;
}
if (currentObject) {
result.push({ instance: currentObject, property: objProp });
} else {
break;
}
// do not need to dive into last object property getter on binding stage will handle it
if (!currentObjectChanged && (i < propsArrayLength - 1)) {
currentObject = currentObject ? currentObject[propsArray[i]] : null;
}
currentObjectChanged = false;
}
return result;
}
private addPropertyChangeListeners(source: WeakRef<Object>, sourceProperty: Array<string>) {
var objectsAndProperties = this.resolveObjectsAndProperties(source.get(), sourceProperty)
var objectsAndPropertiesLength = objectsAndProperties.length;
if (objectsAndPropertiesLength > 0) {
var i;
for (i = 0; i < objectsAndPropertiesLength; i++) {
var prop = objectsAndProperties[i].property;
var currentObject = objectsAndProperties[i].instance;
if (!this.propertyChangeListeners[prop] && currentObject instanceof observable.Observable) {
weakEvents.addWeakEventListener(
currentObject,
observable.Observable.propertyChangeEvent,
this.onSourcePropertyChanged,
this);
this.propertyChangeListeners[prop] = currentObject;
}
}
}
}
public unbind() {
if (!this.source) {
return;
}
var i;
var propertyChangeListenersKeys = Object.keys(this.propertyChangeListeners);
for (i = 0; i < propertyChangeListenersKeys.length; i++) {
weakEvents.removeWeakEventListener(
this.propertyChangeListeners[propertyChangeListenersKeys[i]],
observable.Observable.propertyChangeEvent,
this.onSourcePropertyChanged,
this);
delete this.propertyChangeListeners[propertyChangeListenersKeys[i]];
}
if (this.source) {
this.source.clear();
}
if (this.sourceOptions) {
this.sourceOptions.instance.clear();
this.sourceOptions = undefined;
}
if (this.targetOptions) {
this.targetOptions = undefined;
}
this.sourcePropertiesArray = undefined;
}
private prepareExpressionForUpdate(): string {
// this regex is used to create a valid RegExp object from a string that has some special regex symbols like [,(,$ and so on.
// Basically this method replaces all matches of 'source property' in expression with '$newPropertyValue'.
// For example: with an expression similar to:
// text="{{ sourceProperty = $parents['ListView'].test, expression = $parents['ListView'].test + 2}}"
// update expression will be '$newPropertyValue + 2'
// then on expression execution the new value will be taken and target property will be updated with the value of the expression.
var escapedSourceProperty = utils.escapeRegexSymbols(this.options.sourceProperty);
var expRegex = new RegExp(escapedSourceProperty, 'g');
var resultExp = this.options.expression.replace(expRegex, bc.newPropertyValueKey);
return resultExp;
}
public updateTwoWay(value: any) {
if (this.updating) {
return;
}
if (this.options.twoWay) {
if (this.options.expression) {
var changedModel = {};
changedModel[bc.bindingValueKey] = value;
changedModel[bc.newPropertyValueKey] = value;
var sourcePropertyName = "";
if (this.sourceOptions) {
sourcePropertyName = this.sourceOptions.property;
}
else if (typeof this.options.sourceProperty === "string" && this.options.sourceProperty.indexOf(".") === -1) {
sourcePropertyName = this.options.sourceProperty;
}
if (sourcePropertyName !== "") {
changedModel[sourcePropertyName] = value;
}
var updateExpression = this.prepareExpressionForUpdate();
this.prepareContextForExpression(changedModel, updateExpression);
var expressionValue = this._getExpressionValue(updateExpression, true, changedModel);
if (expressionValue instanceof Error) {
trace.write((<Error>expressionValue).message, trace.categories.Binding, trace.messageType.error);
}
else {
this.updateSource(expressionValue);
}
}
else {
this.updateSource(value);
}
}
}
private _getExpressionValue(expression: string, isBackConvert: boolean, changedModel: any): any {
try {
ensureExpressions();
var exp = expressions.PolymerExpressions.getExpression(expression);
if (exp) {
var context = this.source && this.source.get && this.source.get() || global;
var model = {};
ensureApplication();
for (var prop in application.resources) {
if (application.resources.hasOwnProperty(prop) && !context.hasOwnProperty(prop)) {
context[prop] = application.resources[prop];
}
}
this.prepareContextForExpression(context, expression);
model[contextKey] = context;
return exp.getValue(model, isBackConvert, changedModel ? changedModel : model);
}
return new Error(expression + " is not a valid expression.");
}
catch (e) {
var errorMessage = "Run-time error occured in file: " + e.sourceURL + " at line: " + e.line + " and column: " + e.column;
return new Error(errorMessage);
}
}
public onSourcePropertyChanged(data: observable.PropertyChangeData) {
if (this.options.expression) {
var expressionValue = this._getExpressionValue(this.options.expression, false, undefined);
if (expressionValue instanceof Error) {
trace.write((<Error>expressionValue).message, trace.categories.Binding, trace.messageType.error);
}
else {
this.updateTarget(expressionValue);
}
} else {
var propIndex = this.getSourceProperties().indexOf(data.propertyName);
if (propIndex > -1) {
var props = this.getSourceProperties().slice(propIndex + 1);
var propsLength = props.length;
if (propsLength > 0) {
var value = data.value;
var i;
for (i = 0; i < propsLength; i++) {
value = value[props[i]];
}
this.updateTarget(value);
}
else if (data.propertyName === this.sourceOptions.property) {
this.updateTarget(data.value);
}
}
}
var sourceProps = Binding.getProperties(this.options.sourceProperty);
var sourcePropsLength = sourceProps.length;
var changedPropertyIndex = sourceProps.indexOf(data.propertyName);
if (changedPropertyIndex > -1) {
var probablyChangedObject = this.propertyChangeListeners[sourceProps[changedPropertyIndex + 1]];
if (probablyChangedObject &&
probablyChangedObject !== data.object[sourceProps[changedPropertyIndex]]) {
// remove all weakevent listeners after change, because changed object replaces object that is hooked for
// propertyChange event
for (i = sourcePropsLength - 1; i > changedPropertyIndex; i--) {
weakEvents.removeWeakEventListener(
this.propertyChangeListeners[sourceProps[i]],
observable.Observable.propertyChangeEvent,
this.onSourcePropertyChanged,
this);
delete this.propertyChangeListeners[sourceProps[i]];
}
//var newProps = this.options.sourceProperty.substr(this.options.sourceProperty.indexOf(data.propertyName) + data.propertyName.length + 1);
var newProps = sourceProps.slice(changedPropertyIndex + 1);
// add new weakevent listeners
this.addPropertyChangeListeners(new WeakRef(data.object[sourceProps[changedPropertyIndex]]), newProps);
}
}
}
private prepareContextForExpression(model, expression) {
var parentViewAndIndex;
var parentView;
if (expression.indexOf(bc.bindingValueKey) > -1) {
model[bc.bindingValueKey] = model;
}
if (expression.indexOf(bc.parentValueKey) > -1) {
parentView = this.getParentView(this.target.get(), bc.parentValueKey).view;
if (parentView) {
model[bc.parentValueKey] = parentView.bindingContext;
}
}
var parentsArray = expression.match(bindingBuilder.parentsRegex);
if (parentsArray) {
var i;
for (i = 0; i < parentsArray.length; i++) {
parentViewAndIndex = this.getParentView(this.target.get(), parentsArray[i]);
if (parentViewAndIndex.view) {
model[bc.parentsValueKey] = model[bc.parentsValueKey] || {};
model[bc.parentsValueKey][parentViewAndIndex.index] = parentViewAndIndex.view.bindingContext;
}
}
}
}
private getSourcePropertyValue() {
if (this.options.expression) {
var changedModel = {};
changedModel[bc.bindingValueKey] = this.source.get();
var expressionValue = this._getExpressionValue(this.options.expression, false, changedModel);
if (expressionValue instanceof Error) {
trace.write((<Error>expressionValue).message, trace.categories.Binding, trace.messageType.error);
}
else {
return expressionValue;
}
}
if (!this.sourceOptions) {
this.sourceOptions = this.resolveOptions(this.source, this.getSourceProperties());
}
var value;
if (this.sourceOptions) {
var sourceOptionsInstance = this.sourceOptions.instance.get();
if (this.sourceOptions.property === bc.bindingValueKey) {
value = sourceOptionsInstance;
} else if ((sourceOptionsInstance instanceof observable.Observable) && (this.sourceOptions.property && this.sourceOptions.property !== "")) {
value = sourceOptionsInstance.get(this.sourceOptions.property);
} else if (sourceOptionsInstance && this.sourceOptions.property && this.sourceOptions.property !== "" &&
this.sourceOptions.property in sourceOptionsInstance) {
value = sourceOptionsInstance[this.sourceOptions.property];
} else {
trace.write("Property: '" + this.sourceOptions.property + "' is invalid or does not exist. SourceProperty: '" + this.options.sourceProperty + "'", trace.categories.Binding, trace.messageType.error);
}
}
return value;
}
private updateTarget(value: any) {
if (this.updating || (!this.target || !this.target.get())) {
return;
}
if (!this.targetOptions) {
this.targetOptions = this.resolveOptions(this.target, Binding.getProperties(this.options.targetProperty));
}
this.updateOptions(this.targetOptions, value);
}
private updateSource(value: any) {
if (this.updating || (!this.source || !this.source.get())) {
return;
}
if (!this.sourceOptions) {
this.sourceOptions = this.resolveOptions(this.source, this.getSourceProperties());
}
this.updateOptions(this.sourceOptions, value);
}
private getParentView(target, property) {
if (!target || !(target instanceof viewModule.View)) {
return { view: null, index: null };
}
var result;
if (property === bc.parentValueKey) {
result = target.parent;
}
if (property.indexOf(bc.parentsValueKey) === 0) {
result = target.parent;
var indexParams = paramsRegex.exec(property);
var index;
if (indexParams && indexParams.length > 1) {
index = indexParams[2];
}
if (!isNaN(index)) {
var indexAsInt = parseInt(index);
while (indexAsInt > 0) {
result = result.parent;
indexAsInt--;
}
} else if (types.isString(index)) {
while (result && result.typeName !== index) {
result = result.parent;
}
}
}
return { view: result, index: index };
}
private resolveOptions(obj: WeakRef<any>, properties: Array<string>): { instance: any; property: any } {
var objectsAndProperties = this.resolveObjectsAndProperties(obj.get(), properties);
if (objectsAndProperties.length > 0) {
var resolvedObj = objectsAndProperties[objectsAndProperties.length - 1].instance;
var prop = objectsAndProperties[objectsAndProperties.length - 1].property;
return {
instance: new WeakRef(resolvedObj),
property: prop
}
}
return null;
}
private updateOptions(options: { instance: WeakRef<any>; property: any }, value: any) {
var optionsInstance;
if (options && options.instance) {
optionsInstance = options.instance.get();
}
if (!optionsInstance) {
return;
}
this.updating = true;
try {
if (optionsInstance instanceof Bindable &&
viewModule.isEventOrGesture(options.property, optionsInstance) &&
types.isFunction(value)) {
// calling off method with null as handler will remove all handlers for options.property event
optionsInstance.off(options.property, null, optionsInstance.bindingContext);
optionsInstance.on(options.property, value, optionsInstance.bindingContext);
} else {
ensureSpecialProperties();
let specialSetter = specialProperties.getSpecialPropertySetter(options.property);
if (specialSetter) {
specialSetter(optionsInstance, value);
} else {
if (optionsInstance instanceof observable.Observable) {
optionsInstance.set(options.property, value);
} else {
optionsInstance[options.property] = value;
}
}
}
}
catch (ex) {
trace.write("Binding error while setting property " + options.property + " of " + optionsInstance + ": " + ex,
trace.categories.Binding,
trace.messageType.error);
}
this.updating = false;
}
}