You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

395 lines
14 KiB

  1. // # Semantic Modules
  2. // This particular pattern is useful for describing a group of elements which share behavior, for example a modal or a popup.
  3. // The module is made up of three parts: *a group definition*, *a singular definition*, and a *settings object*.
  4. //
  5. // 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.
  6. // [Read more about coding conventions](#)
  7. /*
  8. * # Semantic Module 1.0
  9. * http://github.com/quirkyinc/semantic
  10. *
  11. *
  12. * Copyright 2013 Contributors
  13. * Released under the MIT license
  14. * http://opensource.org/licenses/MIT
  15. *
  16. * Released: April 17 2013
  17. */
  18. ;(function ( $, window, document, undefined ) {
  19. $.fn.example = function(parameters) {
  20. // ## Group
  21. // Some properties remain constant across all instances of a module.
  22. var
  23. // Store a reference to the module group, this can be useful to refer to other modules inside each module
  24. $allModules = $(this),
  25. // Extend settings to merge run-time settings with defaults
  26. settings = ( $.isPlainObject(parameters) )
  27. ? $.extend(true, {}, $.fn.example.settings, parameters)
  28. : $.fn.example.settings,
  29. // Define namespaces for storing module instance and binding events
  30. eventNamespace = '.' + settings.namespace,
  31. moduleNamespace = 'module-' + settings.namespace,
  32. // Preserve selector from outside each scope and mark current time for performance tracking
  33. moduleSelector = $allModules.selector || '',
  34. time = new Date().getTime(),
  35. performance = [],
  36. // Preserve original arguments to determine if a method is being invoked
  37. query = arguments[0],
  38. methodInvoked = (typeof query == 'string'),
  39. queryArguments = [].slice.call(arguments, 1),
  40. invokedResponse
  41. ;
  42. // ## Singular
  43. // Iterate over all elements to initialize module
  44. $allModules
  45. .each(function() {
  46. var
  47. // Cache selectors using selector definitions for access inside instance of module
  48. $module = $(this),
  49. $text = $module.find(settings.selector.text),
  50. // Define private variables which can be used to maintain internal state, these cannot be changed from outside the module closure so use conservatively
  51. foo = false,
  52. // Define variables used to track module state. Default values are set using `a || b` syntax
  53. instance = $module.data(moduleNamespace),
  54. element = this,
  55. // Alias settings object for convenience and performance
  56. namespace = settings.namespace,
  57. error = settings.error,
  58. className = settings.className,
  59. // You may also find it useful to alias your own settings
  60. text = settings.text,
  61. module
  62. ;
  63. // ## Module Behavior
  64. module = {
  65. // ### Required
  66. // #### Initialize
  67. // Initialize attaches events and preserves each instance in html metadata
  68. initialize: function() {
  69. module.debug('Initializing module for', element);
  70. $module
  71. .on('click' + eventNamespace, module.exampleBehavior)
  72. ;
  73. module.instantiate();
  74. },
  75. instantiate: function() {
  76. module.verbose('Storing instance of module');
  77. // 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
  78. instance = module;
  79. $module
  80. .data(moduleNamespace, instance)
  81. ;
  82. },
  83. // #### Destroy
  84. // Removes all events and the instance copy from metadata
  85. destroy: function() {
  86. module.verbose('Destroying previous module for', element);
  87. $module
  88. .removeData(moduleNamespace)
  89. .off(eventNamespace)
  90. ;
  91. },
  92. // #### Refresh
  93. // Selectors are cached so we sometimes need to manually refresh the cache
  94. refresh: function() {
  95. module.verbose('Refreshing selector cache for', element);
  96. $module = $(element);
  97. $text = $(this).find(settings.selector.text);
  98. },
  99. // ### Custom
  100. // #### By Event
  101. // Sometimes it makes sense to call an event handler by its type if it is dependent on the event to behave properly
  102. event: {
  103. click: function(event) {
  104. module.verbose('Preventing default action');
  105. if( !$module.hasClass(className.disabled) ) {
  106. module.behavior();
  107. }
  108. event.preventDefault();
  109. }
  110. },
  111. // #### By Function
  112. // Other times events make more sense for methods to be called by their function if it is ambivalent to how it is invoked
  113. behavior: function() {
  114. module.debug('Changing the text to a new value', text);
  115. if( !module.has.text() ) {
  116. module.set.text( text);
  117. }
  118. },
  119. // #### Vocabulary
  120. // Custom methods should be defined with consistent vocabulary some useful terms: "has", "set", "get", "change", "add", "remove"
  121. //
  122. // This makes it easier for new developers to get to know your module without learning your schema
  123. has: {
  124. text: function(state) {
  125. module.verbose('Checking whether text state exists', state);
  126. if( text[state] === undefined ) {
  127. module.error(error.noText);
  128. return false;
  129. }
  130. return true;
  131. }
  132. },
  133. set: {
  134. text: function(state) {
  135. module.verbose('Setting text to new state', state);
  136. if( module.has.text(state) ) {
  137. $text
  138. .text( text[state] )
  139. ;
  140. settings.onChange();
  141. }
  142. }
  143. },
  144. // ### Standard
  145. // #### Setting
  146. // Module settings can be read or set using this method
  147. //
  148. // 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
  149. // `$(.foo').example('setting', 'moduleName');`
  150. setting: function(name, value) {
  151. if(value !== undefined) {
  152. if( $.isPlainObject(name) ) {
  153. $.extend(true, settings, name);
  154. }
  155. else {
  156. settings[name] = value;
  157. }
  158. }
  159. else {
  160. return settings[name];
  161. }
  162. },
  163. // #### Internal
  164. // Module internals can be set or retrieved as well
  165. // `$(.foo').example('internal', 'behavior', function() { // do something });`
  166. internal: function(name, value) {
  167. if(value !== undefined) {
  168. if( $.isPlainObject(name) ) {
  169. $.extend(true, module, name);
  170. }
  171. else {
  172. module[name] = value;
  173. }
  174. }
  175. else {
  176. return module[name];
  177. }
  178. },
  179. // #### Debug
  180. // Debug pushes arguments to the console formatted as a debug statement
  181. debug: function() {
  182. if(settings.debug) {
  183. module.performance.log(arguments[0]);
  184. module.debug = Function.prototype.bind.call(console.info, console, settings.moduleName + ':');
  185. }
  186. },
  187. // #### Verbose
  188. // Calling verbose internally allows for additional data to be logged which can assist in debugging
  189. verbose: function() {
  190. if(settings.verbose && settings.debug) {
  191. module.performance.log(arguments[0]);
  192. module.verbose = Function.prototype.bind.call(console.info, console, settings.moduleName + ':');
  193. }
  194. },
  195. // #### Error
  196. // 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.
  197. error: function() {
  198. if(console.log !== undefined) {
  199. module.error = Function.prototype.bind.call(console.log, console, settings.moduleName + ':');
  200. }
  201. },
  202. // #### Performance
  203. // This is called on each debug statement and logs the time since the last debug statement.
  204. performance: {
  205. log: function(message) {
  206. var
  207. currentTime,
  208. executionTime,
  209. previousTime
  210. ;
  211. if(settings.performance) {
  212. currentTime = new Date().getTime();
  213. previousTime = time || currentTime,
  214. executionTime = currentTime - previousTime,
  215. time = currentTime;
  216. performance.push({
  217. 'Name' : message,
  218. 'Execution Time' : executionTime
  219. });
  220. clearTimeout(module.performance.timer);
  221. module.performance.timer = setTimeout(module.performance.display, 100);
  222. }
  223. },
  224. // Performance data is assumed to be complete 500ms after the last log message receieved
  225. display: function() {
  226. var
  227. title = settings.moduleName,
  228. caption = settings.moduleName + ': ' + moduleSelector + '(' + $allModules.size() + ' elements)',
  229. totalExecutionTime = 0
  230. ;
  231. if(moduleSelector) {
  232. title += ' Performance (' + moduleSelector + ')';
  233. }
  234. if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
  235. console.groupCollapsed(title);
  236. if(console.table) {
  237. $.each(performance, function(index, data) {
  238. totalExecutionTime += data['Execution Time'];
  239. });
  240. console.table(performance);
  241. }
  242. else {
  243. $.each(performance, function(index, data) {
  244. totalExecutionTime += data['Execution Time'];
  245. console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
  246. });
  247. }
  248. console.log('Total Execution Time:', totalExecutionTime +'ms');
  249. console.groupEnd();
  250. performance = [];
  251. time = false;
  252. }
  253. }
  254. },
  255. // #### Invoke
  256. // Invoke is used to lookup and invoke a method or property by a dot notation string definition, for example
  257. // `$('.foo').example('invoke', 'set.text', 'Foo')`
  258. invoke: function(query, passedArguments, context) {
  259. var
  260. maxDepth,
  261. found
  262. ;
  263. passedArguments = passedArguments || queryArguments;
  264. context = element || context;
  265. if(typeof query == 'string' && instance !== undefined) {
  266. query = query.split(/[\. ]/);
  267. maxDepth = query.length - 1;
  268. $.each(query, function(depth, value) {
  269. if( $.isPlainObject( instance[value] ) && (depth != maxDepth) ) {
  270. instance = instance[value];
  271. }
  272. else if( instance[value] !== undefined ) {
  273. found = instance[value];
  274. }
  275. else {
  276. module.error(error.method);
  277. }
  278. });
  279. }
  280. if ( $.isFunction( found ) ) {
  281. instance.verbose('Executing invoked function', found);
  282. return found.apply(context, passedArguments);
  283. }
  284. return found || false;
  285. }
  286. };
  287. // ### Determining Intent
  288. // Invoking a method directly
  289. // $('.foo').module('set.text', 'Ho hum');
  290. // The module checks to see if you passed in a method name to call
  291. if(methodInvoked) {
  292. if(instance === undefined) {
  293. module.initialize();
  294. }
  295. invokedResponse = module.invoke(query);
  296. }
  297. // If you didn't pass in anything it can assume you are initializing the module
  298. else {
  299. if(instance !== undefined) {
  300. module.destroy();
  301. }
  302. module.initialize();
  303. }
  304. })
  305. ;
  306. // lets performance tracking know this is the end of a single trace through module
  307. time = false;
  308. // If you called invoke, you may have a returned value which shoudl be returned, otherwise allow the call to chain
  309. return (invokedResponse)
  310. ? invokedResponse
  311. : this
  312. ;
  313. };
  314. // ## Settings
  315. // It is necessary to include a settings object which specifies the defaults for your module
  316. $.fn.example.settings = {
  317. // ### Required
  318. // Used in debug statements to refer to the module itself
  319. name : 'Example Module',
  320. // Whether debug content should be outputted to console
  321. debug : true,
  322. // Whether extra debug content should be outputted
  323. verbose : false,
  324. // Whether to track performance data
  325. performance : false,
  326. // A unique identifier used to namespace events,and preserve the module instance
  327. namespace : 'example',
  328. // ### Optional
  329. // Selectors used by your module
  330. selector : {
  331. example : '.example'
  332. },
  333. // Error messages returned by the module
  334. error: {
  335. noText : 'The text you tried to display has not been defined.',
  336. method : 'The method you called is not defined.'
  337. },
  338. // Class names which your module refers to
  339. className : {
  340. disabled : 'disabled'
  341. },
  342. // Metadata stored or retrieved by your module. `$('.foo').data('value');`
  343. metadata: {
  344. notUsed: 'notUsed'
  345. },
  346. // ### Callbacks
  347. // Callbacks are often useful to include in your settings object
  348. onChange : function() {},
  349. // ### Definition Specific
  350. // You may also want to include settings specific to your module's function
  351. text: {
  352. hover : 'You are hovering me now',
  353. click : 'You clicked on me'
  354. }
  355. };
  356. })( jQuery, window , document );