Skip to content
  • P
    Projects
  • G
    Groups
  • S
    Snippets
  • Help

李洋 / 消息系统

  • This project
    • Loading...
  • Sign in
Go to a project
  • Project
  • Repository
  • Issues 0
  • Merge Requests 0
  • Pipelines
  • Wiki
  • Snippets
  • Settings
  • Activity
  • Graph
  • Charts
  • Create a new issue
  • Jobs
  • Commits
  • Issue Boards
  • Files
  • Commits
  • Branches
  • Tags
  • Contributors
  • Graph
  • Compare
  • Charts
Find file
Normal viewHistoryPermalink
Switch branch/tag
  • CMS-Message
  • public
  • js
  • plugins
  • chosen-ajax-addition
  • example
  • chosen.ajaxaddition.jquery.js
chosen.ajaxaddition.jquery.js 8.09 KB
李洋's avatar
Initial commit
60b5dc25
 
李洋 committed 7 years ago
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:false, bitwise:true, strict:true, undef:true, curly:true, browser:true, indent:4, maxerr:50, onevar:false, nomen:false, regexp:false, plusplus:false, newcap:true */
(function ($) {
	"use strict";
	//Thanks John - http://ejohn.org/blog/javascript-array-remove/
	var arrayRemove = function (from, to) {
		var rest = this.slice((to || from) + 1 || this.length);
		this.length = from < 0 ? this.length + from : from;
		return this.push.apply(this, rest);
	};
	$.fn.ajaxChosen = function (ajaxOptions, options, chosenOptions) {
		var select = $(this),
				chosen,
				keyRight,
				input,
				inputBG,
				callback,
				throttle = false,
				requestQueue = [],
				typing = false,
				loadingImg = '/img/loading.gif',
				minLength = 1;

		if ($('option', select).length === 0) {
			//adding empty option so you don't have to, and chosen can perform search correctly
			select.append('<option value=""></option>');
		}
		if (chosenOptions) {
			select.chosen(chosenOptions);
		} else {
			select.chosen();
		}
		chosen = select.next();
		input = $('input', chosen);
		inputBG = input.get(0) ? input.get(0).style.background : '';
		//copy out success callback
		if ('success' in ajaxOptions && $.isFunction(ajaxOptions.success)) {
			callback = ajaxOptions.success;
		}
		//replace with our success callback
		ajaxOptions.success = function (data, textStatus, jqXHR) {
			var items = data,
					selected, valuesArray, valuesHash = {},
					requestQueueLength = requestQueue.length,
					old = false,
					keep = false,
					inputEmptied = false,
					inputEmptiedValue = '';
			if (typing) {
				//server returned a response, but it's about to become an older response
				//so discard it and wait until the user is done typing
				requestQueue.shift();
				return false;
			}
			if (requestQueueLength > 1) {
				$.each(requestQueue, function (idx, elem) {
					if (data.q === elem) {
						if (idx !== (requestQueueLength - 1)) {
							//found an older response, remove it from the queue and wait for newest response
							old = true;
							arrayRemove.call(requestQueue, idx);
						} else {
							//this handles the out of order request/response
							//last request came in first, and we want to keep it
							keep = true;
							//remove all the other older requests
							requestQueue.length = 0;
						}
						return false;
					}
				});
				//if we found an old response or we found the newest response and want to keep processing
				if (old || !keep) { return false; }
			} else {
				//only 1 request was made by the user remove it from queue and continue processing
				if (typeof requestQueue.shift() === 'undefined') {
					//If all the old responses have been discarded because we've received the new one already
					return false;
				}
			}
			//while the request was processing did the user "empty" the input box
			inputEmptiedValue = $.trim(input.val());//if we have a minLength > 1 then we have to preserve the value (TODO::watch out for potential XSS/other breakages)
			inputEmptied = inputEmptiedValue.length < minLength;

			//if additional processing needs to occur on the returned json
			if ('processItems' in options && $.isFunction(options.processItems)) {
				items = options.processItems(data);
			} else if ('results' in items) {
				//default behavior if process items isn't defined
				//expects there to be a results key in data returned that has the results of the search
				items = items.results;
			} else {
				console.log('Expected results key in data, but was not found. Options could not be built');
				return false;
			}
			//.chzn-choices is only present with multi-selects
			selected = $('option:selected', select).not(':empty').clone().attr('selected', true);
			//saving values for deduplication
			if (!$.isArray(select.val())) {
				valuesArray = [select.val()];
			} else {
				valuesArray = select.val();
			}
			$.each(valuesArray, function (i, value) {
				valuesHash[value] = 1;
			});
			$('option', select).remove();

			$('<option value=""/>').appendTo(select);
			//appending this even on single select in the event the user changes their mind and input is blurred. Keeps selected option selected
			selected.appendTo(select);

			if (!inputEmptied) {
				if ($.isArray(items)) {
					//array of kv pairs [{id:'', text:''}...]
					$.each(items, function (i, opt) {
						if (typeof valuesHash[opt.id] === 'undefined') {
							$('<option value="' + opt.id + '">' + opt.text + '</option>').appendTo(select);
						}
					});
				} else {
					//hash of kv pairs {'id':'text'...}
					$.each(items, function (value, text) {
						if (typeof valuesHash[value] === 'undefined') {
							$('<option value="' + value + '">' + text + '</option>').appendTo(select);
						}
					});
				}
			}
			//update chosen
			select.trigger("chosen:updated");
			//right key, for highlight options after ajax is performed
			keyRight = $.Event('keyup');
			keyRight.which = 39;
			//highlight
			input.val(!inputEmptied ? data.q : inputEmptiedValue).trigger(keyRight).get(0).style.background = inputBG;

			if (items.length > 0) {
				$('.no-results', chosen).hide();
			} else {
				$('.no-results', chosen).show();
			}

			//fire original success
			if (callback) {
				callback(data, textStatus, jqXHR);
			}
		};
		//set loading image
		options || (options = {});
		if ('loadingImg' in options) {
			loadingImg = options.loadingImg;
		}
		//set minimum length that will trigger autocomplete
		if ('minLength' in options) {
			minLength = options.minLength;
		}

    $('.chosen-search > input, .chosen-choices .search-field input', chosen).
      bind('keyup', processValue).
      bind('paste', function (e) {
        var that = this;
        setTimeout(function() {
          processValue.call(that, e);
        }, 50);
      });

    function processValue(e) {
			var field = $(this),
					q = field.val();

			//don't fire ajax if...
			if ((e.type === 'paste' && field.is(':not(:focus)')) ||
        (e.which && (
				(e.which ===  9)  ||//Tab
				(e.which === 13)  ||//Enter
				(e.which === 16)  ||//Shift
				(e.which === 17)  ||//Ctrl
				(e.which === 18)  ||//Alt
				(e.which === 19)  ||//Pause, Break
				(e.which === 20)  ||//CapsLock
				(e.which === 27)  ||//Esc
				(e.which === 33)  ||//Page Up
				(e.which === 34)  ||//Page Down
				(e.which === 35)  ||//End
				(e.which === 36)  ||//Home
				(e.which === 37)  ||//Left arrow
				(e.which === 38)  ||//Up arrow
				(e.which === 39)  ||//Right arrow
				(e.which === 40)  ||//Down arrow
				(e.which === 44)  ||//PrntScrn
				(e.which === 45)  ||//Insert
				(e.which === 144) ||//NumLock
				(e.which === 145) ||//ScrollLock
				(e.which === 91)  ||//WIN Key (Start)
				(e.which === 93)  ||//WIN Menu
				(e.which === 224) ||//command key
				(e.which >= 112 && e.which <= 123)//F1 to F12
			))) { return false; }
			//backout of ajax dynamically
			if ('useAjax' in options && $.isFunction(options.useAjax)) {
				if (!options.useAjax(e)) { return false; }
			}
			//hide no results
			$('.no-results', chosen).hide();
			//backout if nothing is in input box
			if ($.trim(q).length < minLength) {
				input.get(0).style.background = inputBG;
				if (throttle) { clearTimeout(throttle); }
				return false;
			}

			typing = true;

			//add query to data
			if ($.isArray(ajaxOptions.data)) {
				//array
				if (ajaxOptions.data[ajaxOptions.data.length - 1].name === 'q') {
					ajaxOptions.data.pop();
				}
				ajaxOptions.data = ajaxOptions.data.concat({ name: 'q', value: q});
			} else {
				//hash
				if (!('data' in ajaxOptions)) {
					ajaxOptions.data = {};
				}
				$.extend(ajaxOptions.data, { q: q});
			}

            $.extend(ajaxOptions.data, { _ : Date.now() });

			//dynamically generate url
			if ('generateUrl' in options && $.isFunction(options.generateUrl)) {
				ajaxOptions.url = options.generateUrl(q);
			}

			//show loading
			input.get(0).style.background = 'transparent url("' + loadingImg + '") no-repeat right 3px';
			//throttle that bitch, so we don't kill the server
			if (throttle) { clearTimeout(throttle); }
			throttle = setTimeout(function () {
				requestQueue.push(q);
				typing = false;
				$.ajax(ajaxOptions);
			}, 700);
		};

		return select;
	};
})(jQuery);