Better ways to writing JavaScript
Better ways to writing JavaScript
function get(el) {
return document.getElementById(el);
}
//usage:
$('foo', 'bar', 'baz');
var addEvent = function() {
if (window.addEventListener) {
return function(el, type, fn) {
el.addEventListener(type, fn, false);
};
} else if (window.attachEvent) {
return function(el, type, fn) {
var f = function() {
fn.call(el, window.event);
};
el.attachEvent('on' + type, f);
};
}
}();
//usage:
addEvent(get('example'), 'click', function(e) {
alert('hello world');
});
var asyncRequest = function() {
function handleReadyState(o, callback) {
if (o && o.readyState == 4 && o.status == 200) {
if (callback) {
callback(o);
}
}
}
var getXHR = function() {
var http;
try {
http = new XMLHttpRequest;
getXHR = function() {
return new XMLHttpRequest;
};
}
catch(e) {
var msxml = [
‘MSXML2.XMLHTTP.3.0′,
‘MSXML2.XMLHTTP’,
‘Microsoft.XMLHTTP’
];
for (var i=0, len = msxml.length; i < len; ++i) {
try {
http = new ActiveXObject(msxml[i]);
getXHR = function() {
return new ActiveXObject(msxml[i]);
};
break;
}
catch(e) {}
}
}
return http;
};
return function(method, uri, callback, postData) {
var http = getXHR();
http.open(method, uri, true);
handleReadyState(http, callback);
http.send(postData || null);
return http;
};
}();
usage:
asyncRequest('GET', 'test.php?foo=bar', callback);
function callback(o) {
alert(o.responseText);
}
沒有留言:
張貼留言