This repository is currently being migrated. It's locked while the migration is in progress.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
intent.js
126 lines (102 loc) · 3.16 KB
/
intent.js
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
define(['underscore'], function (_) {
var baseIntent = {
DEBUG: false,
/**
* Intent type
* @type {String}
*/
type: null,
/**
* Data passed to intent. Can be anything but most cases should
* be as as simple as possible
* @type {Mixed}
*/
data: {},
args: [],
/**
* Component that sent the intent.
* @type {Component}
*/
origin: null,
/**
* Method that sender expects to be called when intent is handled
*
* Context (this) is always the sender component. Callbacks should
* always have following interface callback(err, args*).
* @type {Function}
*/
respondCallback: null,
/**
* Is Intent sent
* @type {Boolean}
*/
sent: false,
/**
* Is callback called
* @type {Boolean}
*/
handled: false,
/**
* Creates new intent
*
* @param {String} type Intent type
* @param {Mixed} [data] Data
* @return {Intent}
*/
create: function(type, data) {
if (this.DEBUG) console.info('INTENT create: ' + type);
var intent = Object.create(baseIntent);
var args = Array.prototype.slice.call(arguments, 1);
intent.type = type;
intent.data = data;
intent.args = args;
return intent;
},
/**
* Broadcasts the intent
*
*
* @param {Component|Application} [origin] Component that triggered intent
* @param {Function} [respondCallback] Function called in respond
*/
send: function(origin, respondCallback) {
if (this.DEBUG) console.info('INTENT send: ' + this.type, this);
if (this.sent) throw 'Intent already sent';
Object.defineProperty(this, 'origin', {
value: origin
});
Object.defineProperty(this, 'respondCallback', {
value: respondCallback
});
Object.defineProperty(this, 'sent', {
value: true
});
// Ensure context of the respond method
this.respond = _.bind(baseIntent.respond, this);
this._application.sendIntent(this);
},
/**
* Responds to the intent triggering callback if set
*
* Pass respond data as arguments.
*/
respond: function() {
if (this.DEBUG) console.info('INTENT respond: ' + this.type, arguments);
if (this.origin && this.respondCallback) {
Object.defineProperty(this, 'handled', {
value: true
});
var inst = this,
args = arguments;
_.defer(function() {
inst.respondCallback.apply(inst.origin, args);
});
}
},
setDebug: function () {
this.DEBUG = true;
return this;
}
};
return baseIntent;
});