Skip to content

Instantly share code, notes, and snippets.

@hex-ci
Last active April 28, 2016 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hex-ci/cca033089a710c54acfa3b8a6de7e54c to your computer and use it in GitHub Desktop.
Save hex-ci/cca033089a710c54acfa3b8a6de7e54c to your computer and use it in GitHub Desktop.
/**
* 将源对象的属性并入到目标对象
* @method mix
* @static
* @param {Object} des 目标对象
* @param {Object} src 源对象
* @param {boolean} override (Optional) 是否覆盖已有属性。如果为function则初为混合器,为src的每一个key执行 des[key] = override(des[key], src[key], key);
* @returns {Object} des
*/
var mix = function(des, src, override) {
var i;
if (typeof override == 'function') {
for (i in src) {
des[i] = override(des[i], src[i], i);
}
}
else {
for (i in src) {
//这里要加一个des[i],是因为要照顾一些不可枚举的属性
if (override || !(des[i] || (i in des))) {
des[i] = src[i];
}
}
}
return des;
};
// 高级输入框
// 1. 自定义 onInput 事件
var advInputBox = function(element, options) {
var timer1 = null;
var timer2 = null;
var lastValue = '';
var inputId = '';
var exports = {};
element = $(element);
var defaultOptions = {
// 检测间隔
interval: 100,
// 输入延时
delay: 500,
scope: exports,
oninput: $.noop
};
mix(options = options || {}, defaultOptions);
var onTimer = function() {
if ($('#' + inputId).length == 0) {
exports.destroy();
return;
}
var value = element.val();
if (value == lastValue) {
return;
}
lastValue = value;
timer2 = clearTimeout(timer2);
timer2 = setTimeout($.proxy(options.oninput, options.scope, value, element), options.delay);
};
// 使用自定义 onInput 事件
inputId = 'advanced_input_' + ((new Date()).getTime() + Math.floor(Math.random()*9999));
element.attr('id', inputId);
lastValue = element.val();
timer1 = setInterval($.proxy(onTimer, options.scope), options.interval);
mix(exports, {
destroy: function() {
clearInterval(timer1);
clearTimeout(timer2);
},
reset: function(value) {
value = value || '';
clearInterval(timer1);
clearTimeout(timer2);
lastValue = value;
timer1 = setInterval($.proxy(onTimer, options.scope), options.interval);
element.val(value);
}
});
return exports;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment