angular.js/src/Browser.js

62 lines
1.3 KiB
JavaScript
Raw Normal View History

2010-04-04 00:04:36 +00:00
//////////////////////////////
// Browser
//////////////////////////////
2010-04-05 18:46:53 +00:00
function Browser(location, XHR) {
2010-04-04 00:04:36 +00:00
this.location = location;
this.delay = 25;
2010-04-05 18:46:53 +00:00
this.XHR = XHR;
2010-04-04 00:04:36 +00:00
this.setTimeout = function(fn, delay) {
window.setTimeout(fn, delay);
};
this.expectedUrl = location.href;
this.listeners = [];
}
Browser.prototype = {
2010-04-05 18:46:53 +00:00
xhr: function(method, url, callback){
var xhr = new this.XHR();
xhr.open(method, url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.status, xhr.responseText);
}
};
xhr.send('');
},
2010-04-04 00:04:36 +00:00
watchUrl: function(fn){
this.listeners.push(fn);
},
startUrlWatcher: function() {
var self = this;
(function pull () {
if (self.expectedUrl !== self.location.href) {
foreach(self.listeners, function(listener){
2010-04-05 18:46:53 +00:00
try {
listener(self.location.href);
} catch (e) {
error(e);
}
2010-04-04 00:04:36 +00:00
});
self.expectedUrl = self.location.href;
}
self.setTimeout(pull, self.delay);
})();
},
setUrl: function(url) {
var existingURL = this.location.href;
if (!existingURL.match(/#/))
existingURL += '#';
if (existingURL != url)
this.location.href = url;
},
getUrl: function() {
return this.location.href;
}
};