Skip to content

Instantly share code, notes, and snippets.

@djbender
Forked from maccman/reloader.coffee
Created September 24, 2014 19:21
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 djbender/7b733f3975602e495700 to your computer and use it in GitHub Desktop.
Save djbender/7b733f3975602e495700 to your computer and use it in GitHub Desktop.
class @Reloader
constructor: (@selector = '.wrapper', @path, @interval = 2000) ->
@start()
start: =>
@timer = setInterval(@fetch, @interval)
stop: =>
clearInterval(@timer)
fetch: =>
$.get(@path).done(@render)
render: (data) =>
$body = $(@parseBody(data))
if @selector is 'body'
$el = $body
else
$el = @findAll($body, @selector)
$(@selector).replaceWith($el)
parseHTML: (html) =>
$.parseHTML(html, document, false)
parseBody: (data) =>
@parseHTML(data.match(/<body[^>]*>([\s\S.]*)<\/body>/i)[0])
findAll: ($elems, selector) ->
$elems.filter(selector).add($elems.find(selector))
// Generated by CoffeeScript 1.8.0
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
this.Reloader = (function() {
function Reloader(selector, path, interval) {
this.selector = selector != null ? selector : '.wrapper';
this.path = path;
this.interval = interval != null ? interval : 2000;
this.parseBody = __bind(this.parseBody, this);
this.parseHTML = __bind(this.parseHTML, this);
this.render = __bind(this.render, this);
this.fetch = __bind(this.fetch, this);
this.stop = __bind(this.stop, this);
this.start = __bind(this.start, this);
}
Reloader.prototype.start = function() {
return this.timer = setInterval(this.fetch, this.interval);
};
Reloader.prototype.stop = function() {
return clearInterval(this.timer);
};
Reloader.prototype.fetch = function() {
return $.get(this.path).done(this.render);
};
Reloader.prototype.render = function(data) {
var $body, $el;
$body = $(this.parseBody(data));
if (this.selector === 'body') {
$el = $body;
} else {
$el = this.findAll($body, this.selector);
}
return $(this.selector).replaceWith($el);
};
Reloader.prototype.parseHTML = function(html) {
return $.parseHTML(html, document, false);
};
Reloader.prototype.parseBody = function(data) {
return this.parseHTML(data.match(/<body[^>]*>([\s\S.]*)<\/body>/i)[0]);
};
Reloader.prototype.findAll = function($elems, selector) {
return $elems.filter(selector).add($elems.find(selector));
};
return Reloader;
})();
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment