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.

434 lines
15 KiB

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