Skip to content

Instantly share code, notes, and snippets.

@poulet42
Created June 28, 2017 08:13
Show Gist options
  • Save poulet42/7ea316750102c52dc506478e1660e8a1 to your computer and use it in GitHub Desktop.
Save poulet42/7ea316750102c52dc506478e1660e8a1 to your computer and use it in GitHub Desktop.
;(function($, document, window, undefined) {
var defaultOptions = {
endpoint: null,
transformResponse: function(response) {return response;},
method: 'GET',
mod: 'default'
},
pluginName = 'komplete',
pluginVersion = "0.0.1";
var _modifiers = {
'default': function(cb) {
return function () {
cb.apply(this, arguments)
}
},
'debounce': function (cb, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
if (timer) clearTimeout(timer);
timer = setTimeout(function () {
cb.apply(context, args);
}, delay);
};
},
'throttle': function(cb, delay) {
var timer = null, lastTime;
return function() {
var curr = +new Date, context = this;
if (lastTime && curr < lastTime + delay) {
clearTimeout(timer);
timer = setTimeout(function() {
lastTime = curr;
cb.apply(this, arguments)
}, delay)
}
else {
lastTime = curr;
cb.apply(context, arguments);
}
}
}
};
var Plugin = function(element, options) {
this.opts = $.extend({}, defaultOptions, options);
this.$el = $(element);
this.init();
};
$.extend(Plugin.prototype, {
init: function() {
console.log('el : ', this.$el)
this.$input = this.$el.find('input');
this.ajaxKey =
this.$input.data('kompletekey')
|| this.opts.ajaxKey
|| "keywords";
this.observeInput();
console.log('init OK', this.ajaxKey);
},
observeInput: function() {
var mod = this.opts.mod;
this.$input.on('keyup', _modifiers[mod](this.onInput.bind(this), 500))
},
onInput: function(e) {
var val = e.currentTarget.value;
this.requestEndpoint(val)
.done(function(result) {
//appel
})
},
requestEndpoint: function(keywords) {
if (this.opts.method == 'GET') {
return $.get(this.opts.endpoint + "?" + this.ajaxKey + "=" + encodeURI(keywords))
} else {
return $.ajax({
method: this.opts.method,
url: this.opts.endpoint,
data: {[this.ajaxKey]: keywords}
})
}
}
});
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new Plugin( this, options ));
}
});
}
})(jQuery, document, window, undefined)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment