angular.js/src/Browser.js

97 lines
2.4 KiB
JavaScript
Raw Normal View History

2010-04-04 00:04:36 +00:00
//////////////////////////////
// Browser
//////////////////////////////
2010-04-06 03:53:33 +00:00
function Browser(location, document) {
2010-04-04 00:04:36 +00:00
this.delay = 25;
2010-04-06 03:53:33 +00:00
this.expectedUrl = location.href;
this.urlListeners = [];
this.hoverListener = noop;
this.XHR = XMLHttpRequest || function () {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
2010-04-04 00:04:36 +00:00
this.setTimeout = function(fn, delay) {
window.setTimeout(fn, delay);
};
2010-04-06 03:53:33 +00:00
this.location = location;
this.document = jqLite(document);
this.body = jqLite(document.body);
2010-04-04 00:04:36 +00:00
}
Browser.prototype = {
2010-04-06 03:53:33 +00:00
bind: function() {
var self = this;
self.document.bind("mouseover", function(event){
self.hoverListener(jqLite(event.target), true);
return true;
});
self.document.bind("mouseleave mouseout click dblclick keypress keyup", function(event){
self.hoverListener(jqLite(event.target), false);
return true;
});
},
hover: function(hoverListener) {
this.hoverListener = hoverListener;
},
addCss: function(url) {
var head = jqLite(this.document[0].getElementsByTagName('head')[0]),
link = jqLite('<link rel="stylesheet" type="text/css"></link>');
link.attr('href', url);
head.append(link);
},
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){
2010-04-06 03:53:33 +00:00
this.urlListeners.push(fn);
2010-04-04 00:04:36 +00:00
},
startUrlWatcher: function() {
var self = this;
(function pull () {
if (self.expectedUrl !== self.location.href) {
2010-04-06 03:53:33 +00:00
foreach(self.urlListeners, 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;
2010-04-16 21:01:29 +00:00
if (!existingURL.match(/#/)) existingURL += '#';
if (!url.match(/#/)) url += '#';
if (existingURL != url) {
this.location.href = this.expectedUrl = url;
}
2010-04-04 00:04:36 +00:00
},
getUrl: function() {
return this.location.href;
}
};