Created
August 5, 2016 17:46
-
-
Save yaodong/facfab730d7dfc84bd4bdf58e630aca3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const $ = require("jquery"); | |
class TurboLink { | |
constructor(el, opts) { | |
this.$link = $(el); | |
this.opts = opts; | |
this.sendRequest(); | |
} | |
getLink() { | |
return this.$link; | |
} | |
sendRequest() { | |
const targetSelector = this.getTargetSelector(); | |
const requestUrl = this.getRequestUrl(); | |
this.$link.click((e) => { | |
e.preventDefault(); | |
$.ajax({ | |
url: requestUrl, | |
dataType: 'html', | |
success: (data, textStatus, jqXHR) => { | |
let replaceWith = $(data).find(targetSelector); | |
if (replaceWith) { | |
$(targetSelector).replaceWith(replaceWith); | |
this.triggerEvent('success'); | |
} | |
}, | |
beforeSend: () => { | |
this.triggerEvent('start'); | |
}, | |
error: () => { | |
this.triggerEvent('error'); | |
}, | |
complete: () => { | |
this.triggerEvent('complete'); | |
} | |
}); | |
}); | |
} | |
triggerEvent(name) { | |
if (this.opts['events'][name]) { | |
this.opts['events'][name](this) | |
} | |
} | |
getTargetSelector() { | |
if (this.opts['target']) { | |
return this.opts['target']; | |
} else if (this.$link.hasData('turbolink-target')) { | |
return this.$link.data('turbolink-target'); | |
} else { | |
return undefined; | |
} | |
} | |
getRequestUrl() { | |
if (this.opts['url']) { | |
return this.opts['url']; | |
} else if (this.$link.attr('href')) { | |
return this.$link.attr('href') | |
} else { | |
return undefined; | |
} | |
} | |
} | |
module.exports = TurboLink; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment