Skip to content

Instantly share code, notes, and snippets.

@futjikato
Created September 25, 2012 19:45
Show Gist options
  • Save futjikato/3784000 to your computer and use it in GitHub Desktop.
Save futjikato/3784000 to your computer and use it in GitHub Desktop.
LinkHasher jQuery Plugin
/**
* jQuery Hashlink plugin
* @copyright 2012 Moritz Spindelhirn
*/
;
(function($){
var pluginName = 'hashlink',
dataName = 'jq.plugin.' + pluginName,
events = ['Load', 'BeforeLoad', 'Click'],
defaultConf = {
prefix : '/#!/',
attr : 'href',
target : '#container',
onClick : function() {
$(this).data(dataName).load();
}
};
function LinkHasher(elem, conf) {
this.host = $(elem);
this.conf = conf;
// hash link
if($(elem).attr(conf.attr)) {
this.hash();
}
}
LinkHasher.prototype.getConf = function() {
return this.conf;
};
LinkHasher.prototype.hash = function() {
var attr = this.host.attr(this.conf.attr);
if(!attr || !attr.length) return;
attr = (attr.substr(0, 1) == '/') ? attr.substr(1) : attr;
attr = (attr.indexOf(this.conf.prefix) == 0) ? attr : this.conf.prefix + attr;
this.host.attr(this.conf.attr, attr);
};
LinkHasher.prototype.unhash = function() {
var attr = this.host.attr(this.conf.attr);
if(!attr) return;
return (attr.indexOf(this.conf.prefix) == 0) ? attr.replace(this.conf.prefix, '') : attr;
};
LinkHasher.prototype.load = function() {
var host = this.host,
conf = this.conf;
// trigger on before load
var event = $.Event('beforeload');
host.trigger(event);
if(event.isDefaultPrevented()) {
return;
}
$.ajax({
url : this.unhash(),
success : function(res) {
var event = $.Event('load', { ajaxResult: res });
host.trigger(event);
if(event.isDefaultPrevented()) {
return;
}
$(conf.target).html(res);
}
});
};
$.fn[pluginName] = function(opts) {
var conf = $.extend({}, defaultConf, opts) ;
return this.each(function(){
var $this = $(this);
if(!$.data(this, dataName)) {
$.data(this, dataName, new LinkHasher(this, conf));
// bind events
for(var i in events) {
var eventName = events[i];
if(conf['on' + eventName]) {
$this.on(eventName.toLowerCase(), conf['on' + eventName]);
}
}
}
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment