Last active
April 28, 2016 06:38
-
-
Save hex-ci/cca033089a710c54acfa3b8a6de7e54c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 将源对象的属性并入到目标对象 | |
* @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