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.

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