rating.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. /*!
  2. * # Fomantic-UI - Rating
  3. * http://github.com/fomantic/Fomantic-UI/
  4. *
  5. *
  6. * Released under the MIT license
  7. * http://opensource.org/licenses/MIT
  8. *
  9. */
  10. ;(function ($, window, document, undefined) {
  11. 'use strict';
  12. $.isFunction = $.isFunction || function(obj) {
  13. return typeof obj === "function" && typeof obj.nodeType !== "number";
  14. };
  15. window = (typeof window != 'undefined' && window.Math == Math)
  16. ? window
  17. : (typeof self != 'undefined' && self.Math == Math)
  18. ? self
  19. : Function('return this')()
  20. ;
  21. $.fn.rating = function(parameters) {
  22. var
  23. $allModules = $(this),
  24. moduleSelector = $allModules.selector || '',
  25. time = new Date().getTime(),
  26. performance = [],
  27. query = arguments[0],
  28. methodInvoked = (typeof query == 'string'),
  29. queryArguments = [].slice.call(arguments, 1),
  30. returnedValue
  31. ;
  32. $allModules
  33. .each(function() {
  34. var
  35. settings = ( $.isPlainObject(parameters) )
  36. ? $.extend(true, {}, $.fn.rating.settings, parameters)
  37. : $.extend({}, $.fn.rating.settings),
  38. namespace = settings.namespace,
  39. className = settings.className,
  40. metadata = settings.metadata,
  41. selector = settings.selector,
  42. eventNamespace = '.' + namespace,
  43. moduleNamespace = 'module-' + namespace,
  44. element = this,
  45. instance = $(this).data(moduleNamespace),
  46. $module = $(this),
  47. $icon = $module.find(selector.icon),
  48. initialLoad,
  49. module
  50. ;
  51. module = {
  52. initialize: function() {
  53. module.verbose('Initializing rating module', settings);
  54. if($icon.length === 0) {
  55. module.setup.layout();
  56. }
  57. if(settings.interactive && !module.is.disabled()) {
  58. module.enable();
  59. }
  60. else {
  61. module.disable();
  62. }
  63. module.set.initialLoad();
  64. module.set.rating( module.get.initialRating() );
  65. module.remove.initialLoad();
  66. module.instantiate();
  67. },
  68. instantiate: function() {
  69. module.verbose('Instantiating module', settings);
  70. instance = module;
  71. $module
  72. .data(moduleNamespace, module)
  73. ;
  74. },
  75. destroy: function() {
  76. module.verbose('Destroying previous instance', instance);
  77. module.remove.events();
  78. $module
  79. .removeData(moduleNamespace)
  80. ;
  81. },
  82. refresh: function() {
  83. $icon = $module.find(selector.icon);
  84. },
  85. setup: {
  86. layout: function() {
  87. var
  88. maxRating = module.get.maxRating(),
  89. icon = module.get.icon(),
  90. html = $.fn.rating.settings.templates.icon(maxRating, icon)
  91. ;
  92. module.debug('Generating icon html dynamically');
  93. $module
  94. .html(html)
  95. ;
  96. module.refresh();
  97. }
  98. },
  99. event: {
  100. mouseenter: function() {
  101. var
  102. $activeIcon = $(this)
  103. ;
  104. $activeIcon
  105. .nextAll()
  106. .removeClass(className.selected)
  107. ;
  108. $module
  109. .addClass(className.selected)
  110. ;
  111. $activeIcon
  112. .addClass(className.selected)
  113. .prevAll()
  114. .addClass(className.selected)
  115. ;
  116. },
  117. mouseleave: function() {
  118. $module
  119. .removeClass(className.selected)
  120. ;
  121. $icon
  122. .removeClass(className.selected)
  123. ;
  124. },
  125. click: function() {
  126. var
  127. $activeIcon = $(this),
  128. currentRating = module.get.rating(),
  129. rating = $icon.index($activeIcon) + 1,
  130. canClear = (settings.clearable == 'auto')
  131. ? ($icon.length === 1)
  132. : settings.clearable
  133. ;
  134. if(canClear && currentRating == rating) {
  135. module.clearRating();
  136. }
  137. else {
  138. module.set.rating( rating );
  139. }
  140. }
  141. },
  142. clearRating: function() {
  143. module.debug('Clearing current rating');
  144. module.set.rating(0);
  145. },
  146. bind: {
  147. events: function() {
  148. module.verbose('Binding events');
  149. $module
  150. .on('mouseenter' + eventNamespace, selector.icon, module.event.mouseenter)
  151. .on('mouseleave' + eventNamespace, selector.icon, module.event.mouseleave)
  152. .on('click' + eventNamespace, selector.icon, module.event.click)
  153. ;
  154. }
  155. },
  156. remove: {
  157. events: function() {
  158. module.verbose('Removing events');
  159. $module
  160. .off(eventNamespace)
  161. ;
  162. },
  163. initialLoad: function() {
  164. initialLoad = false;
  165. }
  166. },
  167. enable: function() {
  168. module.debug('Setting rating to interactive mode');
  169. module.bind.events();
  170. $module
  171. .removeClass(className.disabled)
  172. ;
  173. },
  174. disable: function() {
  175. module.debug('Setting rating to read-only mode');
  176. module.remove.events();
  177. $module
  178. .addClass(className.disabled)
  179. ;
  180. },
  181. is: {
  182. initialLoad: function() {
  183. return initialLoad;
  184. },
  185. disabled: function() {
  186. return $module.hasClass(className.disabled);
  187. }
  188. },
  189. get: {
  190. icon: function(){
  191. var icon = $module.data(metadata.icon);
  192. if (icon) {
  193. $module.removeData(metadata.icon);
  194. }
  195. return icon || settings.icon;
  196. },
  197. initialRating: function() {
  198. if($module.data(metadata.rating) !== undefined) {
  199. $module.removeData(metadata.rating);
  200. return $module.data(metadata.rating);
  201. }
  202. return settings.initialRating;
  203. },
  204. maxRating: function() {
  205. if($module.data(metadata.maxRating) !== undefined) {
  206. $module.removeData(metadata.maxRating);
  207. return $module.data(metadata.maxRating);
  208. }
  209. return settings.maxRating;
  210. },
  211. rating: function() {
  212. var
  213. currentRating = $icon.filter('.' + className.active).length
  214. ;
  215. module.verbose('Current rating retrieved', currentRating);
  216. return currentRating;
  217. }
  218. },
  219. set: {
  220. rating: function(rating) {
  221. var
  222. ratingIndex = (rating - 1 >= 0)
  223. ? (rating - 1)
  224. : 0,
  225. $activeIcon = $icon.eq(ratingIndex)
  226. ;
  227. $module
  228. .removeClass(className.selected)
  229. ;
  230. $icon
  231. .removeClass(className.selected)
  232. .removeClass(className.active)
  233. ;
  234. if(rating > 0) {
  235. module.verbose('Setting current rating to', rating);
  236. $activeIcon
  237. .prevAll()
  238. .addBack()
  239. .addClass(className.active)
  240. ;
  241. }
  242. if(!module.is.initialLoad()) {
  243. settings.onRate.call(element, rating);
  244. }
  245. },
  246. initialLoad: function() {
  247. initialLoad = true;
  248. }
  249. },
  250. setting: function(name, value) {
  251. module.debug('Changing setting', name, value);
  252. if( $.isPlainObject(name) ) {
  253. $.extend(true, settings, name);
  254. }
  255. else if(value !== undefined) {
  256. if($.isPlainObject(settings[name])) {
  257. $.extend(true, settings[name], value);
  258. }
  259. else {
  260. settings[name] = value;
  261. }
  262. }
  263. else {
  264. return settings[name];
  265. }
  266. },
  267. internal: function(name, value) {
  268. if( $.isPlainObject(name) ) {
  269. $.extend(true, module, name);
  270. }
  271. else if(value !== undefined) {
  272. module[name] = value;
  273. }
  274. else {
  275. return module[name];
  276. }
  277. },
  278. debug: function() {
  279. if(!settings.silent && settings.debug) {
  280. if(settings.performance) {
  281. module.performance.log(arguments);
  282. }
  283. else {
  284. module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
  285. module.debug.apply(console, arguments);
  286. }
  287. }
  288. },
  289. verbose: function() {
  290. if(!settings.silent && settings.verbose && settings.debug) {
  291. if(settings.performance) {
  292. module.performance.log(arguments);
  293. }
  294. else {
  295. module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
  296. module.verbose.apply(console, arguments);
  297. }
  298. }
  299. },
  300. error: function() {
  301. if(!settings.silent) {
  302. module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
  303. module.error.apply(console, arguments);
  304. }
  305. },
  306. performance: {
  307. log: function(message) {
  308. var
  309. currentTime,
  310. executionTime,
  311. previousTime
  312. ;
  313. if(settings.performance) {
  314. currentTime = new Date().getTime();
  315. previousTime = time || currentTime;
  316. executionTime = currentTime - previousTime;
  317. time = currentTime;
  318. performance.push({
  319. 'Name' : message[0],
  320. 'Arguments' : [].slice.call(message, 1) || '',
  321. 'Element' : element,
  322. 'Execution Time' : executionTime
  323. });
  324. }
  325. clearTimeout(module.performance.timer);
  326. module.performance.timer = setTimeout(module.performance.display, 500);
  327. },
  328. display: function() {
  329. var
  330. title = settings.name + ':',
  331. totalTime = 0
  332. ;
  333. time = false;
  334. clearTimeout(module.performance.timer);
  335. $.each(performance, function(index, data) {
  336. totalTime += data['Execution Time'];
  337. });
  338. title += ' ' + totalTime + 'ms';
  339. if(moduleSelector) {
  340. title += ' \'' + moduleSelector + '\'';
  341. }
  342. if($allModules.length > 1) {
  343. title += ' ' + '(' + $allModules.length + ')';
  344. }
  345. if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
  346. console.groupCollapsed(title);
  347. if(console.table) {
  348. console.table(performance);
  349. }
  350. else {
  351. $.each(performance, function(index, data) {
  352. console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
  353. });
  354. }
  355. console.groupEnd();
  356. }
  357. performance = [];
  358. }
  359. },
  360. invoke: function(query, passedArguments, context) {
  361. var
  362. object = instance,
  363. maxDepth,
  364. found,
  365. response
  366. ;
  367. passedArguments = passedArguments || queryArguments;
  368. context = element || context;
  369. if(typeof query == 'string' && object !== undefined) {
  370. query = query.split(/[\. ]/);
  371. maxDepth = query.length - 1;
  372. $.each(query, function(depth, value) {
  373. var camelCaseValue = (depth != maxDepth)
  374. ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
  375. : query
  376. ;
  377. if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
  378. object = object[camelCaseValue];
  379. }
  380. else if( object[camelCaseValue] !== undefined ) {
  381. found = object[camelCaseValue];
  382. return false;
  383. }
  384. else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
  385. object = object[value];
  386. }
  387. else if( object[value] !== undefined ) {
  388. found = object[value];
  389. return false;
  390. }
  391. else {
  392. return false;
  393. }
  394. });
  395. }
  396. if ( $.isFunction( found ) ) {
  397. response = found.apply(context, passedArguments);
  398. }
  399. else if(found !== undefined) {
  400. response = found;
  401. }
  402. if(Array.isArray(returnedValue)) {
  403. returnedValue.push(response);
  404. }
  405. else if(returnedValue !== undefined) {
  406. returnedValue = [returnedValue, response];
  407. }
  408. else if(response !== undefined) {
  409. returnedValue = response;
  410. }
  411. return found;
  412. }
  413. };
  414. if(methodInvoked) {
  415. if(instance === undefined) {
  416. module.initialize();
  417. }
  418. module.invoke(query);
  419. }
  420. else {
  421. if(instance !== undefined) {
  422. instance.invoke('destroy');
  423. }
  424. module.initialize();
  425. }
  426. })
  427. ;
  428. return (returnedValue !== undefined)
  429. ? returnedValue
  430. : this
  431. ;
  432. };
  433. $.fn.rating.settings = {
  434. name : 'Rating',
  435. namespace : 'rating',
  436. icon : 'star',
  437. silent : false,
  438. debug : false,
  439. verbose : false,
  440. performance : true,
  441. initialRating : 0,
  442. interactive : true,
  443. maxRating : 4,
  444. clearable : 'auto',
  445. fireOnInit : false,
  446. onRate : function(rating){},
  447. error : {
  448. method : 'The method you called is not defined',
  449. noMaximum : 'No maximum rating specified. Cannot generate HTML automatically'
  450. },
  451. metadata: {
  452. rating : 'rating',
  453. maxRating : 'maxRating',
  454. icon : 'icon'
  455. },
  456. className : {
  457. active : 'active',
  458. disabled : 'disabled',
  459. selected : 'selected',
  460. loading : 'loading'
  461. },
  462. selector : {
  463. icon : '.icon'
  464. },
  465. templates: {
  466. icon: function(maxRating, iconClass) {
  467. var
  468. icon = 1,
  469. html = ''
  470. ;
  471. while(icon <= maxRating) {
  472. html += '<i class="'+iconClass+' icon"></i>';
  473. icon++;
  474. }
  475. return html;
  476. }
  477. }
  478. };
  479. })( jQuery, window, document );