forked from Semantic-Org/Semantic-UI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule.commented.js
More file actions
executable file
·431 lines (387 loc) · 15 KB
/
module.commented.js
File metadata and controls
executable file
·431 lines (387 loc) · 15 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
// # Semantic Modules
// This is a design pattern for creating UI modules in Semantic
//
// Semantic is unique in that all arbitrary data is a setting. Semantic modules also are self documenting, with module.debug calls serving to explain state, and log performance data.
// [Read more about coding conventions](http://semantic-ui.com/guide/javascriptguide.html) and [Read about modules](http://semantic-ui.com/module.html)
/*
* # Semantic Module
* http://github.com/quirkyinc/semantic
*
*
* Copyright 2013 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*/
;(function ( $, window, document, undefined ) {
$.fn.example = function(parameters) {
// ## Group
// Some properties remain constant across all instances of a module.
var
// Store a reference to the module group, this can be useful to refer to other modules inside each module
$allModules = $(this),
// Preserve selector from outside each scope and mark current time for performance tracking
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
// Preserve original arguments to determine if a method is being invoked
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
// ## Singular
// Iterate over all elements to initialize module
$allModules
.each(function() {
var
// Extend settings to merge run-time settings with defaults
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.example.settings, parameters)
: $.extend({}, $.fn.example.settings),
// Alias settings object for convenience and performance
namespace = settings.namespace,
error = settings.error,
className = settings.className,
// You may also find it useful to alias your own settings
text = settings.text,
// Define namespaces for storing module instance and binding events
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
// Instance is stored and retreived in namespaced DOM metadata
instance = $(this).data(moduleNamespace),
element = this,
// Cache selectors using selector settings object for access inside instance of module
$module = $(this),
$text = $module.find(settings.selector.text),
// Define private variables which can be used to maintain internal state, these cannot be changed from outside the module closure so use conservatively. Default values are set using `a || b` syntax
foo = false,
module
;
// ## Module Behavior
module = {
// ### Required
// #### Initialize
// Initialize attaches events and preserves each instance in html metadata
initialize: function() {
module.debug('Initializing module for', element);
$module
.on('click' + eventNamespace, module.exampleBehavior)
;
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of module');
// The instance is just a copy of the module definition, we store it in metadata so we can use it outside of scope, but also define it for immediate use
instance = module;
$module
.data(moduleNamespace, instance)
;
},
// #### Destroy
// Removes all events and the instance copy from metadata
destroy: function() {
module.verbose('Destroying previous module for', element);
$module
.removeData(moduleNamespace)
.off(eventNamespace)
;
},
// #### Refresh
// Selectors or cached values sometimes need to refreshed
refresh: function() {
module.verbose('Refreshing elements', element);
$module = $(element);
$text = $(this).find(settings.selector.text);
},
// ### Custom
// #### By Event
// Sometimes it makes sense to call an event handler by its type if it is dependent on the event to behave properly
event: {
click: function(event) {
module.verbose('Preventing default action');
if( !$module.hasClass(className.disabled) ) {
module.behavior();
}
event.preventDefault();
}
},
// #### By Function
// Other times events make more sense for methods to be called by their function if it is ambivalent to how it is invoked
behavior: function() {
module.debug('Changing the text to a new value', text);
if( !module.has.text() ) {
module.set.text( text);
}
},
// #### Vocabulary
// Custom methods should be defined with consistent vocabulary some useful terms: "has", "set", "get", "change", "add", "remove"
//
// This makes it easier for new developers to get to know your module without learning your schema
has: {
text: function(state) {
module.verbose('Checking whether text state exists', state);
if( text[state] === undefined ) {
module.error(error.noText);
return false;
}
return true;
}
},
set: {
text: function(state) {
module.verbose('Setting text to new state', state);
if( module.has.text(state) ) {
$text
.text( text[state] )
;
settings.onChange();
}
}
},
// ### Standard
// #### Setting
// Module settings can be read or set using this method
//
// Settings can either be specified by modifying the module defaults, by initializing the module with a settings object, or by changing a setting by invoking this method
// `$(.foo').example('setting', 'moduleName');`
setting: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
settings[name] = value;
}
else {
return settings[name];
}
},
// #### Internal
// Module internals can be set or retrieved as well
// `$(.foo').example('internal', 'behavior', function() { // do something });`
internal: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, module, name);
}
else if(value !== undefined) {
module[name] = value;
}
else {
return module[name];
}
},
// #### Debug
// Debug pushes arguments to the console formatted as a debug statement
debug: function() {
if(settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.debug.apply(console, arguments);
}
}
},
// #### Verbose
// Calling verbose internally allows for additional data to be logged which can assist in debugging
verbose: function() {
if(settings.verbose && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.verbose.apply(console, arguments);
}
}
},
// #### Error
// Error allows for the module to report named error messages, it may be useful to modify this to push error messages to the user. Error messages are defined in the modules settings object.
error: function() {
module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
module.error.apply(console, arguments);
},
// #### Performance
// This is called on each debug statement and logs the time since the last debug statement.
performance: {
log: function(message) {
var
currentTime,
executionTime,
previousTime
;
if(settings.performance) {
currentTime = new Date().getTime();
previousTime = time || currentTime;
executionTime = currentTime - previousTime;
time = currentTime;
performance.push({
'Element' : element,
'Name' : message[0],
'Arguments' : [].slice.call(message, 1) || '',
'Execution Time' : executionTime
});
}
clearTimeout(module.performance.timer);
module.performance.timer = setTimeout(module.performance.display, 100);
},
display: function() {
var
title = settings.name + ':',
totalTime = 0
;
time = false;
clearTimeout(module.performance.timer);
$.each(performance, function(index, data) {
totalTime += data['Execution Time'];
});
title += ' ' + totalTime + 'ms';
if(moduleSelector) {
title += ' \'' + moduleSelector + '\'';
}
if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
console.groupCollapsed(title);
if(console.table) {
console.table(performance);
}
else {
$.each(performance, function(index, data) {
console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
});
}
console.groupEnd();
}
performance = [];
}
},
// #### Invoke
// Invoke is used to match internal functions to string lookups.
// `$('.foo').example('invoke', 'set text', 'Foo')`
// Method lookups are lazy, looking for many variations of a search string
// For example 'set text', will look for both `setText : function(){}`, `set: { text: function(){} }`
// Invoke attempts to preserve the 'this' chaining unless a value is returned.
// If multiple values are returned an array of values matching up to the length of the selector is returned
invoke: function(query, passedArguments, context) {
var
maxDepth,
found,
response
;
passedArguments = passedArguments || queryArguments;
context = element || context;
if(typeof query == 'string' && instance !== undefined) {
query = query.split(/[\. ]/);
maxDepth = query.length - 1;
$.each(query, function(depth, value) {
var camelCaseValue = (depth != maxDepth)
? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
: query
;
if( $.isPlainObject( instance[value] ) && (depth != maxDepth) ) {
instance = instance[value];
}
else if( $.isPlainObject( instance[camelCaseValue] ) && (depth != maxDepth) ) {
instance = instance[camelCaseValue];
}
else if( instance[value] !== undefined ) {
found = instance[value];
return false;
}
else if( instance[camelCaseValue] !== undefined ) {
found = instance[camelCaseValue];
return false;
}
else {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
// ### Invocation response
// If a user passes in multiple elements invoke will be called for each element and the value will be returned in an array
// For example ``$('.things').example('has text')`` with two elements might return ``[true, false]`` and for one element ``true``
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
// ### Determining Intent
// This is where the actual action occurs.
// $('.foo').module('set text', 'Ho hum');
// If you call a module with a string parameter you are most likely trying to invoke a function
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
// if no method call is required we simply initialize the plugin, destroying it if it exists already
else {
if(instance !== undefined) {
module.destroy();
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
// ## Settings
// It is necessary to include a settings object which specifies the defaults for your module
$.fn.example.settings = {
// ### Required
// Used in debug statements to refer to the module itself
name : 'Example Module',
// Whether debug content should be outputted to console
debug : true,
// Whether extra debug content should be outputted
verbose : false,
// Whether to track performance data
performance : false,
// A unique identifier used to namespace events,and preserve the module instance
namespace : 'example',
// ### Optional
// Selectors used by your module
selector : {
example : '.example'
},
// Error messages returned by the module
error: {
noText : 'The text you tried to display has not been defined.',
method : 'The method you called is not defined.'
},
// Class names which your module refers to
className : {
disabled : 'disabled'
},
// Metadata attributes stored or retrieved by your module. `$('.foo').data('value');`
metadata: {
text: 'text'
},
// ### Callbacks
// Callbacks are often useful to include in your settings object
onChange : function() {},
// ### Definition Specific
// You may also want to include settings specific to your module's function
text: {
hover : 'You are hovering me now',
click : 'You clicked on me'
}
};
})( jQuery, window , document );