Skip to content

Instantly share code, notes, and snippets.

@phi-jp
Created March 1, 2013 11:44
Show Gist options
  • Save phi-jp/5064134 to your computer and use it in GitHub Desktop.
Save phi-jp/5064134 to your computer and use it in GitHub Desktop.
watcher.tm.js
/*
* phi
*/
;(function(global) {
global.tm = global.tm || {};
var ajax = function(url, fn) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.responseType = 'text';
xhr.onload = function() {
if (fn) fn(xhr.responseText);
};
xhr.send();
};
tm.Watcher = {
isLocal: (function() { return window.location.href.split('/')[0] === 'file:'; })(),
watch: function(path, frequency) {
path = path || window.location.href;
frequency = frequency || 1000;
if (path.length) {
for (var i=0,len=path.length; i<len; ++i) {
this._observe(path[i], frequency);
}
}
else {
this._observe(path, frequency);
}
},
_observe: function(path, frequency) {
var nowData = null;
// 今のファイルを取得
ajax(path, function(data) {
nowData = data;
});
// 監視
var _observe = function() {
var newData = null;
ajax(path, function(data) { newData = data; });
if (nowData !== newData) {
window.location.reload();
}
};
setInterval(_observe, frequency);
},
ajax: function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false); // 非同期
xhr.responseType = 'text';
xhr.onload = function() {
if (fn) fn(xhr.responseText);
};
xhr.send();
},
};
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment