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.

431 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. if($.isArray(invokedResponse)) {
  313. invokedResponse.push(response);
  314. }
  315. else if(typeof invokedResponse == 'string') {
  316. invokedResponse = [invokedResponse, response];
  317. }
  318. else if(response !== undefined) {
  319. invokedResponse = response;
  320. }
  321. return found;
  322. }
  323. };
  324. // ### Determining Intent
  325. // This is where the actual action occurs.
  326. // $('.foo').module('set text', 'Ho hum');
  327. // If you call a module with a string parameter you are most likely trying to invoke a function
  328. if(methodInvoked) {
  329. if(instance === undefined) {
  330. module.initialize();
  331. }
  332. module.invoke(query);
  333. }
  334. // if no method call is required we simply initialize the plugin, destroying it if it exists already
  335. else {
  336. if(instance !== undefined) {
  337. module.destroy();
  338. }
  339. module.initialize();
  340. }
  341. })
  342. ;
  343. return (invokedResponse !== undefined)
  344. ? invokedResponse
  345. : this
  346. ;
  347. };
  348. // ## Settings
  349. // It is necessary to include a settings object which specifies the defaults for your module
  350. $.fn.example.settings = {
  351. // ### Required
  352. // Used in debug statements to refer to the module itself
  353. name : 'Example Module',
  354. // Whether debug content should be outputted to console
  355. debug : true,
  356. // Whether extra debug content should be outputted
  357. verbose : false,
  358. // Whether to track performance data
  359. performance : false,
  360. // A unique identifier used to namespace events,and preserve the module instance
  361. namespace : 'example',
  362. // ### Optional
  363. // Selectors used by your module
  364. selector : {
  365. example : '.example'
  366. },
  367. // Error messages returned by the module
  368. error: {
  369. noText : 'The text you tried to display has not been defined.',
  370. method : 'The method you called is not defined.'
  371. },
  372. // Class names which your module refers to
  373. className : {
  374. disabled : 'disabled'
  375. },
  376. // Metadata attributes stored or retrieved by your module. `$('.foo').data('value');`
  377. metadata: {
  378. text: 'text'
  379. },
  380. // ### Callbacks
  381. // Callbacks are often useful to include in your settings object
  382. onChange : function() {},
  383. // ### Definition Specific
  384. // You may also want to include settings specific to your module's function
  385. text: {
  386. hover : 'You are hovering me now',
  387. click : 'You clicked on me'
  388. }
  389. };
  390. })( jQuery, window , document );