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.

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