Search

12/30/2007

premature optimization is the root of all evil

Optimization (computer science) - Wikipedia, the free encyclopedia

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.
(Knuth, Donald. Structured Programming with go to Statements, ACM Journal Computing Surveys, Vol 6, No. 4, Dec. 1974. p.268.)
"Premature optimization" is a phrase used to describe a situation where a programmer lets performance considerations affect the design of a piece of code. This can result in a design that is not as clean as it could have been or code that is incorrect, because the code is complicated by the optimization and the programmer is distracted by optimizing.

Cook Computing : Premature Optimization
Its usually not worth spending a lot of time micro-optimizing code before its obvious where the performance bottlenecks are. But, conversely, when designing software at a system level, performance issues should always be considered from the beginning. A good software developer will do this automatically, having developed a feel for where performance issues will cause problems. An inexperienced developer will not bother, misguidedly believing that a bit of fine tuning at a later stage will fix any problems.

12/28/2007

Jash: JavaScript Shell

Jash: JavaScript Shell
Documentation
Firefox上面已經有firebug了, 所以這個東西還是用IE上面比較適合

Jash is a DHTML-based window that gives you command-line JavaScript access to the current browser window. With this console you can quickly debug scripts, manipulate the DOM, view the current page's objects, functions, and variables, trace the execution stack, execute arbitrary Javascript, enter new CSS (in IE, Firefox, Opera, and Safari), and much more.

substring


s = 'http://forum.pcdvd.com.tw/search.php?searchid=7218092&pp=25&page=11'

//find string from 'searchid='
s.substring(s.indexOf('searchid='))
//"searchid=7218092&pp=25&page=11"
s.substring(0, s.indexOf('searchid='))
//"http://forum.pcdvd.com.tw/search.php?"

//find string from 'searchid=' but not include 'searchid='
s.substring(s.indexOf('searchid=') + ('searchid=').length)
//"7218092&pp=25&page=11"

reStructuredText

reStructuredText

reStructuredText is an easy-to-read, what-you-see-is-what-you-get plaintext markup syntax and parser system. It is useful for in-line program documentation (such as Python docstrings), for quickly creating simple web pages, and for standalone documents. reStructuredText is designed for extensibility for specific application domains. The reStructuredText parser is a component of Docutils. reStructuredText is a revision and reinterpretation of the StructuredText and Setext lightweight markup systems.

Cross Domain Frame Communication

Julien Lecomte’s Blog » Introducing CrossFrame, a Safe Communication Mechanism Across Documents and Across Domains
Tagneto: Cross Domain Frame Communication with Fragment Identifiers (for Comet?)

JavaScript and Object Oriented Programming (OOP)

JavaScript and Object Oriented Programming (OOP)
An object constructor is merely a regular JavaScript function, so it's just as robust (ie: define parameters, call other functions etc). The difference between the two is that a constructor function is called via the new operator

function cat(name) {
this.name = name;
this.talk = function() {
alert( this.name + " say meeow!" )
}
}

cat1 = new cat("felix")
cat1.talk() //alerts "felix says meeow!"

cat2 = new cat("ginger")
cat2.talk() //alerts "ginger says meeow!"

We use it when we would like an object to inherit a method after it has been defined. Think of prototyping mentally as "attaching" a method to an object after it's been defined, in which all object instances then instantly share.
cat.prototype.changeName = function(name) {
this.name = name;
}

firstCat = new cat("pursur")
firstCat.changeName("Bill")
firstCat.talk() //alerts "Bill says meeow!"

JavaScript supports prototype inheritance instead of class based. It's possible for inheritance to happen other ways, however.
function superClass() {
this.supertest = superTest; //attach method superTest
}

function subClass() {
this.inheritFrom = superClass;
this.inheritFrom();
this.subtest = subTest; //attach method subTest
}

function superTest() {
return "superTest";
}

function subTest() {
return "subTest";
}


var newClass = new subClass();

alert(newClass.subtest()); // yields "subTest"
alert(newClass.supertest()); // yields "superTest"

javascript access control: private variables

lixo.org :: JavaScript: Put everything in a namespace


var Article = Article ? Article : new Object();
Article.title = “Report: School Shootings Help Prepare Students For Being Shot In Real World”;
Article.save = function() {
alert(”Saving ” + this.title);
}

use the object literal notation directly:


var Article = Article ? Article : {
title: “Report: School Shootings Help Prepare Students For Being Shot In Real World”,
save: function() {
alert(”Saving ” + this.title)
}
}

These two last examples are great if you’re not that concerned about exposing the ‘title’ attribute to the rest of the world. If there is a chance that problems could arise if some other piece of code changed it directly, there is a solution:

var Article = Article ? Article : function() {
var private = {
title: “Report: School Shootings Help Prepare Students For Being Shot In Real World”
};

var public = {
getTitle: function() {
return private.title;
},

save: function() {
alert(”Saving ” + this.getTitle());
}
}

return public;
}();

by creating an anonymous function that returns the object I want to define, and then immediately calling it (note the ‘()’ at the last line), I can hide whatever I don’t want other parts of the code to see - it’s all tucked away in the local context of that anonymous function.

12/27/2007

MyEnTunnel - A background SSH tunnel daemon

MyEnTunnel - A background SSH tunnel daemon

MyEnTunnel is a simple system tray application (or NT service) that establishes and maintains TCP SSH tunnels. It does this by launching Plink (PuTTY Link) in the background and then monitors the process. If the Plink process dies (e.g. connection drops, server restarts or otherwise becomes unreachable) MyEnTunnel will automatically restart Plink to reestablish the tunnels in the background. It tries to use as little CPU and system resources as possible when monitoring (When the "Slow Polling" option is enabled it only does one context switch per second).

<META http-equiv imagetoolbar>


<META HTTP-EQUIV="imagetoolbar" CONTENT="no">

Indicates that the toolbar is not to be shown for all images on the page.

Dean Edwards: Using Google To Serve Faster JavaScript

Dean Edwards: Using Google To Serve Faster JavaScript - free static file hosting & svn version control & wiki document, what could be better?
http://code.google.com/p/deanedwards/
http://deanedwards.googlecode.com/svn/trunk/
用 Google Code 放 Javascript… at Gea-Suan Lin’s BLOG
Update: http://chunghe.googlecode.com/svn/trunk/
修改mime type的方法: HowToBuild - flexlib - Google Code


update: WikiSyntax - support - Google Code
tag: subversion config

scripting select and option

http://chunghe.googlepages.com/select.htm
在select中選擇發生的事件是 onchange, foo.selectedIndex 可以抓到選取項目的 index, 從 0 開始, foo.options[foo.selectedIndex]可以抓取項目的 reference, foo.options[foo.selectedIndex].value可以抓到選取項目的 value, bar.options[i].selected = true 可以選取第 i 項 option

var foo = document.getElementById('foo');
var bar = document.getElementById('bar');
var mapping = {
'programming': 'a',
'surfing' : 'd',
'caffeine' : 'b',
'annoying_ohoh' : 'c',
'thinking' : 'x'
}
foo.onchange = function(){
// get the value of selected item
var selectedValue = foo.options[foo.selectedIndex].value;
if('undefined' === typeof mapping[selectedValue]){
alert(selectedValue + ': no such item');
return
}

// map the select value to another select
var mappingValue = mapping[selectedValue];

// search select 'bar' for the mappingValue
var options = bar.getElementsByTagName('option');
for(var i=0; i<options.length; i++){
if(options[i].value == mappingValue){
bar.options[i].selected = true;
break;
}
}
if(options.length == i){
alert(foo.options[foo.selectedIndex].value + ': no match');
}
}

12/26/2007

location.search & get query string

//location.href
"http://www.example.com/foo.php?userid=someone&book=7"
//location.search
"?userid=someone&book=7"
//location.search.indexOf(1)
"userid=someone&book=7"

/*
* This function parses ampersand-separated name=value argument pairs from
* the query string of the URL. It stores the name=value pairs in
* properties of an object and returns that object. Use it like this:
*
* var args = getArgs( ); // Parse args from URL
* var q = args.q || ""; // Use argument, if defined, or a default value
* var n = args.n ? parseInt(args.n) : 10;
*/
function getArgs( ) {
var args = new Object( );
var query = location.search.substring(1); // Get query string
var pairs = query.split("&"); // Break at ampersand
for(var i = 0; i < pairs.length; i++) {
var pos = pairs[i].indexOf('='); // Look for "name=value"
if (pos == -1) continue; // If not found, skip
var argname = pairs[i].substring(0,pos); // Extract the name
var value = pairs[i].substring(pos+1); // Extract the value
value = decodeURIComponent(value); // Decode it, if needed
args[argname] = value; // Store as a property
}
return args; // Return the object
}

12/25/2007

syntaxhighlighter

終於有syntax highlighting了, powered by syntaxhighlighter - Google Code, 色調是vim desert theme, code 直接看source就有了,http://chunghe.googlepages.com/shCoreJsCss.js Blogger的使用者要看這篇 BloggerMode - syntaxhighlighter - Google Code

dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll('code');

Update: G牌的google-code-prettify

無限猴子定理 - Wikipedia

無限猴子定理 - Wikipedia
Infinite monkey theorem - Wikipedia, the free encyclopedia

無限猴子定理說明,一隻猴子隨機在打字機鍵盤上按鍵,最後必然可以打出法國國家圖書館中的每本書。

OPML (Outline Processor Markup Language)

OPML - Wikipedia, the free encyclopedia - bloglines 可以匯出 OPML 格式的 feeds list 給 google reader吃

OPML (Outline Processor Markup Language) is an XML format for outlines. Originally developed by Radio UserLand as a native file format for an outliner application, it has since been adopted for other uses, the most common being to exchange lists of web feeds between web feed aggregators.

The OPML specification defines an outline as a hierarchical, ordered list of arbitrary elements. The specification is fairly open which makes it suitable for many types of list data.

prototype wrapper for YUI Dom utilities

http://chunghe.googlepages.com/prototype.wrapper.for.YUI.Dom.utilit.htm
用prototype把常用的一些 YUI Dom utilities (getRegion, getXY, getViewportHeight/getViewportWidth, getDocumentScrollTop/getDocumentScrollLeft)重寫一次,還是比較習慣YUI的naming convention,順便熟悉一下在prototype的哪些function mapping到YUI的哪些function。
值得一提的是 document.viewport.getDimensions().width;這個會把viewport width多算'17px',之前在lightbox.js也有遇到一樣的問題,不是很確定,所以用了YUI的code把這部分補起來。另外YUI在IE底下,getXY在X與Y都多算了'2px',prototype算起來倒是正確的。

var PUD = {
getXY: function(ele){
var ele = $(ele);
var pos = ele.positionedOffset();
return [pos.left, pos.top];
},

getRegion: function(ele){
var ele = $(ele);
var pos = ele.positionedOffset();
var t = pos[1];
var r = pos[0] + ele.offsetWidth;
var b = pos[1] + ele.offsetHeight;
var l = pos[0];
return [t, r, b, l];
},

getViewportHeight: function(ele){
return document.viewport.getDimensions().height;
},

getWrongViewportWidth : function(ele){
// belowing method provided by prototype has '17px' margin error
return document.viewport.getDimensions().width;
},

getViewportWidth : function(ele){
// belowing method provided by prototype has '17px' margin error
//return document.viewport.getDimensions().width;
var width = self.innerWidth;
var mode = document.compatMode;

if (mode || Prototype.Browser.IE) { // IE, Gecko, Opera
width = (mode == 'CSS1Compat') ?
document.documentElement.clientWidth : // Standards
document.body.clientWidth; // Quirks
}
return width;
},

getDocumentScrollLeft : function(ele){
return document.viewport.getScrollOffsets()[0];
},

getDocumentScrollTop : function(ele){
return document.viewport.getScrollOffsets()[1];
}
}

12/24/2007

CSS filters vs. conditional comment

css.filters
centricle : css filters (css hacks) - 非常詳細的列出各式樣的 css hacks & filters 以及在不同的 browsers & OSs 下面的情形。

                ie7 ie6
* html div N Y
_property:value Y Y
*property:value N Y

MSDN - About Conditional Comments
Hack-free CSS for IE - Arve Bersvendsen
<link rel="stylesheet" type="text/css" href="common.css" />

<!--[if IE]>
<link rel="stylesheet" type="text/css" href="all-ie.css" />
<![endif]-->

<!--[if IE 6]>
<link rel="stylesheet" type="text/css" href="ie-6.0.css" />
<![endif]-->

<!--[if IE lt 6]>
<link rel="stylesheet" type="text/css" href="ie-5.0+5.5.css" />
<![endif]-->

Mastering JavaScript — concept and resource guide

Mastering JavaScript — concept and resource guide » d’bug - here's a list of advanced javascript.
Access Control
* Private Members in JavaScript
* How to achieve private, public, and privileged members in JavaScript
* Private JavaScript
Closures
* JavaScript Closures for Dummies
* JavaScript Closures
* Closures and executing JavaScript on page load
Classical OOP
* JavaScript Object-Oriented Programming Part 1
* Objectifying JavaScript
* JavaScript and Object Oriented Programming (OOP)
* Douglas Crockford Video: Advanced JavaScript
Namespaces and Self-invoking Functions
* Namespacing your JavaScript
* JavaScript Namespaces
* JavaScript: Put everything in a namespace
Concepts in AJAX
* AJAX Queue Class
* Reusing XMLHttpRequest Object in IE
* AJAX Patterns
* Managing sessions in an Ajax-enabled application

Internet Explorer box model bug

Internet Explorer box model bug - Wikipedia, the free encyclopedia
務必記住用 YUI: YAHOO.util.Dom.getRegion 算出來的 height/width 是整個 box 的 高度/寬度, 也就是包含 padding, border 但不包含 margin

Internet Explorer versions 6 and 7 are not affected by the bug if the page contains certain HTML document type declarations. These versions maintain the buggy behavior when in quirks mode for reasons of backward compatibility.[4] For example, quirks mode is triggered:
* When the document type declaration is absent or incomplete;
* When an HTML 3 or earlier document is encountered;
* When an HTML 4.0 Transitional or Frameset document type declaration is used and a system identifier (URI) is not present;
* When an SGML comment or other unrecognized content appears before the document type declaration, or if there are errors elsewhere in the document;
* Internet Explorer 6 also uses quirks mode if there is an XML declaration prior to the document type declaration.[5]
Box model hacks have proven unreliable because they rely on bugs in browsers' CSS support that may be fixed in later versions. For this reason, some Web developers have instead recommended either avoiding specifying both width and padding for the same element or using conditional comments to work around the box model bug in older versions of Internet Explorer.[6][7]

12/23/2007

How to Win Friends & Influence People

女工程師的紐約生活手札 - "You Speak Good English." "Thank You!"
Amazon.com: How to Win Friends & Influence People: Books: Dale Carnegie

第一章講不要批評抱怨,第二章強調稱讚的重要性。裡面搭配很多政治人物、名人、成功企業家遇到衝突的狀況與如何以智慧的言語化解危機與贏得人心。原來美國這種講話著重稱讚的哲學是其來有自的,書上提到的政治人物、商場企業家都知道要成為成功領導者,通常並不是最有能力的者,而是那個可以有效溝通想法並影響、啟發、說服他人與自己一起朝目標前進的人。而要讓對方能照自己的意思去作,當中很重要的是了解對方的想法,而首當其衝的是誠心的稱讚。每個人都想要追求”A feeling of importance”,能適時誠心的稱讚你的伴侶、小孩、親人、員工、朋友等,不但可以免除很多衝突、不滿、仇恨的情緒,真誠的稱讚也將在對方的腦中如美妙的音樂般,盤旋許久。

12/21/2007

The YUI CSS Foundation

Nate Koechley: "The YUI CSS Foundation&quo - Yahoo! Video
components

  • Reset - a clean foundation(把所有的樣式取消, 包含h1-h6都同樣size, em.strong的效果也都取消.)
  • Fonts - typographical control-> for free(1)arial (2)13px font size (3)16px line height
  • Grids - layout and page control
  • Base - basic helper/snippets lib (把Reset取消的code放回來, 如果要自己design style, 就不需要include這支, 因為production的css會蓋過Base蓋過Reset不太make sense)
fonts.css (font.css在IE下可以改變字型大小的原因是因為apply到後面的*font-size:small & *font:x-small而不是前面的13px)
body {font:13px/1.231 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small;}
table {font-size:inherit;font:100%;}
de,kbd,samp,tt {font-family:monospace;*font-size:108%;line-height:100%;}

grid.css
1. 決定total page width,有下面五種 doc width
(1)#doc 750px, (2)#doc2 950px, (3)#doc3 100%, (4)#doc4 974px, (5)#doc-custom
#doc-custom的作法(1) 決定寬度: ex: 650px (2) 除以13: 46.15em (3) 乘上0.9759: 45.04 em
#custom-doc{
margin:auto;
text-align: left;
width: 46.15em;
*width: 45.04em;
min-width: 600px; /* not necessary but recommanded */
}

2. 決定邊欄的位置&寬度,有以下6種template
(1).yui-t1: 160 left, (2).yui-t2: 180 left, (3).yui-t3 300 left, (4).yui-t4 180 right, (5).yui-t5 240 right, (6).yui-t6 300 right
Two content blocks: yui-b for blocks, 一個是比較寬的main,另一個是比較窄的的邊欄
<div id="doc">
<div class="yui-b"></div>
<div class="yui-b"></div>
</div>

把主要的main用yui-main包起來: identify the main block:
<div id="doc">
<div id="yui-main">
<div class="yui-b"></div>
</div>
<div class="yui-b"></div>
</div>

所以整個結構變成
<div id="doc" class="yui-t3">
<div id="hd"></div>
<div id="bd">
<div id="yui-main">
<div class="yui-b"></div>
</div>
<div class="yui-b"></div>
</div>
<div id="ft"></div>
</div>

3. 建立grid: 第一個yui-u or yui-g要多一個class 'first',用來決定float方向
.yui-g: grid holder
.yui-u: grid units
兩個column,各佔50%
<div class="yui-g">
<div class="yui-u"></div>
<div class="yui-u"></div>
</div>

四個column,各佔25%
<div class="yui-g">
<div class="yui-g first">
<div class="yui-u" first>
<div class="yui-u">
</div>
<div class="yui-g">
<div class="yui-u" first>
<div class="yui-u">
</div>
</div>

uneven grid holder
.yui-gb 1/3 1/3 1/3
.yui-gc 2/3 1/3
.yui-gd 1/3 2/3
.yui ge 3/4 1/4
.yui-gf 1/4 3/4

review
1. Page width: div #doc
2. Templates: .yui-t1
3. Grids: .yui-g .yui-u
4. Fills all space
5. Nestable & stackable

quote

只有两种计算机语言:一些语言天天挨骂,另外一些没有人用。(Bjarne Stroustrup)

http://www.example.com

You have reached this web page by typing "example.com", "example.net", or "example.org" into your web browser.

These domain names are reserved for use in documentation and are not available for registration. See RFC 2606, Section 3.

12/20/2007

when inline css is useful

http://developer.yahoo.com/yui/examples/container/overlay.html

The markup for overlay1, plus the context element ctx and the buttons to show all our Overlays, is displayed below. Note that overlay1 has an inline style of visibility:hidden set in advance. Most browsers are slower to render CSS than inline styles, and we want this marked-up Overlay to be hidden by default. If the inline style isn't present, it may cause a brief "flash of unstyled content" where the Overlay may be visible on slower machines.

比薩塔 Pizza Top:簡約的豐富生活:Xuite日誌

比薩塔 Pizza Top:簡約的豐富生活:Xuite日誌
比薩塔 Pizza Top
台北市金華街181號1樓
(02)2327-8028、23278208
這裡的消費採吃到飽的方式,平日中午(11:00~16:30)220元加一成,晚餐及假日250加一成,都是現烤供應吃到飽

yui useful functions

YAHOO.lang.dump

 var t = {
'who': 'foo',
'email': 'foo@example.com',
'c': function(){
alert( 'who:' + this.who + ' email:' + this.email )
}
}
alert(YAHOO.lang.dump(t));
//{who => foo, email => foo@example.com, c => f(){...}}

YAHOO.lang.trim
Returns a string without any leading or trailing whitespace. If the input is not a string, the input will be returned untouched.

 var t = '  example string  ';
YAHOO.lang.trim(t);
alert('|' + t + '|');
alert('|'+ YAHOO.lang.trim(t) + '|');
//| example string |
//|example string|

12/19/2007

Ajaxian » Unobtrusively Mapping Microformats with jQuery

Ajaxian » Unobtrusively Mapping Microformats with jQuery - jQuery寫起來真好看
最後的成品

Simon puts together jQuery, microformats, and the Google Maps API to grok hCard and show maps of any hCard data that is found, ending up with:
jQuery('.vcard').each(function() {
var hcard = jQuery(this);
var streetaddress = hcard.find('.street-address').text();
var postcode = hcard.find('.postal-code').text();
var geocoder = new MapstractionGeocoder(function(result) {
var marker = new Marker(result.point);
marker.setInfoBubble(
'<div class="bubble">' + hcard.html() + '</div>'
);
mapstraction.addMarker(marker);
}, 'google');
geocoder.geocode({'address': streetaddress + ', ' + postcode});
});

Computed vs Cascaded Style

Computed vs Cascaded Style

function getStyle(el, prop) {
if (document.defaultView && document.defaultView.getComputedStyle) {
return document.defaultView.getComputedStyle(el, null)[prop];
} else if (el.currentStyle) {
return el.currentStyle[prop];
} else {
return el.style[prop];
}
}

So what is wrong with this you might ask?.

div { width: 500px; font-size: 12px; }
p { width: 50%; font-size: 1em; }
a { font-size: inherit; }

<div>
<p id="p">Some text with <a id=a href=#>a link</a>.
More <b style="font-size:150%">text</b></p>
</div>


alert(getStyle(document.getElementById('p'), 'fontSize'));
//ie:1em(cascaded style) ff: 12px(computed style)

alert(getStyle(document.getElementById('p'), 'width'));
//ie:50%(cascaded style) ff:250px(computed style)

All browsers except IE has a way to get the computed style. The way to do
this is to use document.defaultView.getComputedStyle. Only IE has a way to get
the cascaded style. This is done using element.currentStyle.

12/18/2007

The Django Book

The Django Book - great online django book. The comment system is cool as well.
official django tutorial
update: Django pronunciation
update: The Django Book: Version 2.0

12/17/2007

TrueCrypt

TrueCrypt - Free Open-Source On-The-Fly Disk Encryption Software for Windows Vista/XP/2000 and Linux
Free open-source disk encryption software for Windows Vista/XP/2000 and Linux

Main Features:
* Creates a virtual encrypted disk within a file and mounts it as a real disk.
* Encrypts an entire hard disk partition or a storage device such as USB flash drive.
* Encryption is automatic, real-time (on-the-fly) and transparent.
* Provides two levels of plausible deniability, in case an adversary forces you to reveal the password:
1) Hidden volume (steganography – more information may be found here).
2) No TrueCrypt volume can be identified (volumes cannot be distinguished from random data).
* Encryption algorithms: AES-256, Serpent, and Twofish. Mode of operation: LRW.
Further information regarding features of the software may be found in the documentation.

12/10/2007

pre-wrap equivalent

IE/win Expanding Box
Stopping long words destroying layout

Contrary to spec, IE allows very long words to expand a box widthwards - which can then easily destroy a layout if other boxes are floated right.
Add this rule to the box that holds blog comments (or do what I did, and just add it to the body tag):
body {word-wrap: break-word;}

white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */

<nobr> equivalent
.nowrap { white-space: nowrap; }

yui code snippet

The Yahoo! User Interface Library. Simon Willison. XTech Ajax Developer’s Day
Preparatory notes for "The Yahoo! User Interface Library" at XTech
getElementsBy which is more general, taking an acceptance function that is passed each node in turn and must return true or false:

YAHOO.util.Dom.getElementsBy(function(el) {
return (/^http:\/\/www\.yahoo\.com/.test(el.getAttribute('href')));
}));

YAHOO.util.Connect.asyncRequest(
'GET', '/ajaxy-goodness', {
success: function(o) {
alert(o.responseText);
},
failure: function(o) {
alert('Request failed: ' +o.statusText);
}
}
);

As you can see, you pass in an object containing success and failure callback functions. The connection object can also handle scope correction, for example if you want to call methods on a JavaScript object:

YAHOO.util.Connect.asyncRequest('GET', '/ajaxy-goodness', {
success: myObject.onSuccess,
failure: myObject.onFailure,
scope: myObject
});

Custom Event
var myEvent = new YAHOO.util.CustomEvent(
'myEvent'
);
myEvent.subscribe(function() {
alert('event fired');
});
myEvent.fire();


function onSuccess(o) {
alert(o.argument);
}

YAHOO.util.Connect.asyncRequest('GET', '/ajaxy-goodness', {
success: onSuccess,
argument: 'some extra data'
});

onavailable
YAHOO.util.Event.onAvailable(
'mydiv', function() {
alert('mydiv has become available');
}
);

Extra callback arguments
function msgAlert(e, msg) {
alert(msg);
}
YAHOO.util.Event.on(
'mydiv', 'click', msgAlert, "My div was clicked"
);

Reference:
Preparatory notes for "The Yahoo! User Interface Library" at XTech

How to make Ajax work for you

How to make Ajax work for you » SlideShare - simple & clear AJAX codes
How to make Ajax work for you

var xhr = createXHR();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
alert(xhr.responseText);
} else {
alert('Error code ' + xhr.status);
}
}
};
xhr.open('GET', '/helloworld.txt', true);
xhr.send(null);

function createXHR() {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {}
}
return xhr;
}

var xhr = createXHR();
xhr.onreadystatechange = onComplete;
xhr.open('POST', '/helloworld.php', true);
xhr.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded'
);
xhr.send('name=Simon&age=26');

xhr.open('POST', '/helloworld.php', true);
The third argument specifies that we want to make an asynchronous request (“tell me when you’re done by calling this function”). If you set this to false you’ll get a synchronous request, which will completely hang the browser until the request returns. Don’t do that.

function buildQueryString(obj) {
var bits = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
bits[bits.length] = escape(key) + '=' +
escape(obj[key]);
}
}
return bits.join('&');
}
var s = buildQueryString({
name: 'Simon',
age: 26
});
name=Simon&age=26

There's still a complete doRequest function. Keep reading ...
<form id="evil" action="http://example.com/admin/delete.php" method="POST">
<input type="hidden" name="id" value="5">
</form>
<script>
document.getElementById('evil').submit()
</script>

Unobtrusive Javascript、Progressive Enhancement、Gracefully Degrade

从几个与 DOM 脚本编程有关的术语翻译说起

为了给用户更佳的体验,我想做到 Progressive Enhancement。然而,要是人家浏览器不支持怎么办?好吧,那就 Gracefully Degrade 吧。换句话说,Progressive Enhancement 是代表美好理想的新体验,而 Gracefully Degrade 则是面对残酷现实的替代品。

Unobtrusive Javascript
From DHTML to DOM scripting - an example of how to replace outdated JavaScript techniques.

12/09/2007

How to Answer Behavioral Interview Questions

How to Answer Behavioral Interview Questions
Complete List of Behavioral Interview Questions

DOM/JavaScript famous person


Brendan Eich - creator of JavaScript
Blog: Brendan's Roadmap Updates




Chris Heilmann
著作: 《Beginning JavaScript with DOM Scripting and Ajax》
BLOG: Wait till I come!
From DHTML to DOM Scripting



著作: 《DOM Scripting》
Jeremy Keith



Dustin Diaz - founder of CSS Naked Day
著作: 《Pro JavaScript Design Patterns》
Blog: Dustin Diaz: ./with Imagination

12/07/2007

Google Chart API

Developer's Guide - Google Chart API - Google Code - 圖比excel的好看


Mr./Ms. Days (MMDays) - 網路, 資訊, 觀察, 生活 » Blog Archive » 用網址畫圖,Google 推出 Google Chart API
unofficial google rounded corner api
Charts And Graphs: Modern Solutions | Developer's Toolbox | Smashing Magazine
update: there are many tools generating charts visually
Chart Maker - Generator for the Chart Server API
Online Charts Builder
update:
這邊有人寫了一個簡單的proxy把request cache起來
Wait till I come! » Blog Archive » Generating charts from accessible data tables and vice versa using the Google Charts API

Understanding and Solving Internet Explorer Leak Patterns

The problem with innerHTML
Understanding and Solving Internet Explorer Leak Patterns

1. Circular References—When mutual references are counted between Internet Explorer's COM infrastructure and any scripting engine, objects can leak memory. This is the broadest pattern.
2. Closures—Closures are a specific form of circular reference that pose the largest pattern to existing Web application architectures. Closures are easy to spot because they rely on a specific language keyword and can be searched for generically.
3. Cross-Page Leaks—Cross-page leaks are often very small leaks of internal book-keeping objects as you move from site to site. We'll examine the DOM Insertion Order issue, along with a workaround that shows how small changes to your code can prevent the creation of these book-keeping objects.
4. Pseudo-Leaks—These aren't really leaks, but can be extremely annoying if you don't understand where your memory is going. We'll examine the script element rewriting and how it appears to leak quite a bit of memory, when it is really performing as required.

IEBlog : Tools for Detecting Memory Leaks
Drip and sIEve
GPDE Team Blog : JavaScript Memory Leak Detector (v2)
Via: Tsung's Blog | IE 偵測 Memory Leaks 的程式

12/06/2007

microformat & Tails Export :: Firefox Add-ons

Tails Export :: Firefox Add-ons
Operator :: Firefox Add-ons

An extension for Showing and Exporting Microformats.

Can Your
Website be Your API? — All in the head
http://microformats.org/blog/2007/06/21/microformatsorg-turns-2/
First hCard profile import implemented! Mere days ago, Satisfaction Inc. implemented a really nice user interface for signing up (screenshot) that lets you pick your existing hCard-supporting profile on sites like Cork’d, Last FM, Flickr, Technorati, Twitter, Yedda etc. to fill out such basics as your name, your user icon, and URL.

Dopplr friends import screen First XFN+hCard social network import implemented! Mere hours ago, maybe a day ago, Dopplr.com, a currently invite-only travelplan sharing site, implemented the ability to import your contacts from any other site that publishes your contact list with hCard for the people and XFN for your relationship(s) to them, instead of having to manually find and re-add everyone to yet another site. Here is a screenshot of the results.

Examples:
keroro's hCard
http://flickr.com/people/drewm/
http://upcoming.yahoo.com/event/337052/

absolute position的水平&垂直置中

keroro's hCard
在一已知 height & width 的 element,這個技巧蠻不錯的,原理是先設定 top: 50%; left: 50%;,設定 element 的寬與高 height: 18em, width: 30em,再利用 negative margin 把 element shift 寬/高的一半 margin-left: -15em; margin-top: -9em

vcard {
border:1px solid #666666;
height:18em;
left:50%;
margin-left:-15em;
margin-top:-9em;
position:absolute;
top:50%;
width:30em;
}

12/05/2007

YUI 2.4

YUI CSS Selector
Yahoo! UI Library: Selector Utility
cheatsheet

" " Descendant Combinator: “A B”represents an element B that has A as an ancestor.
> Child Combinator: “A > B” represents anelement B whose parent node is A.
+ Direct Adjacent Combinator: “A + B”represents an element B immediately following a sibling element A.
~ Indirect Adjacent Combinator: “A ~ B”represents an element B following (not necessarily immediately following) a sibling element A.


JSON utility - 把 eval() 丟掉吧
// Potentially UNSAFE
var data = eval('(' + shouldBeJsonData + ')');

// Safe
var data = YAHOO.lang.JSON.parse(shouldBeJsonData);

JSON to JavaScript Data
var jsonString = '{"productId":1234,"price":24.5,"inStock":true,"bananas":null}';

// Parsing JSON strings can throw a SyntaxError exception, so we wrap the call
// in a try catch block
try {
var prod = YAHOO.lang.JSON.parse(jsonString);
}
catch (e) {
alert("Invalid product data");
}

// We can now interact with the data
if (prod.price < 25) {
prod.price += 10; // Price increase!
}

JavaScript to JSON
var myData = {
puppies : [
{ name: "Ashley", age: 12 },
{ name: "Abby", age:9 }
]
};

var jsonStr = YAHOO.lang.JSON.stringify(myData);

// jsonStr now contains the string (without the leading comment slashes)
// {"puppies":[{"name":"Ashley","age":12},{"name":"Abby","age":9}]}

// Create a cyclical reference
myData["puppies"][0]["NEWKEY"] = myData;

jsonStr = YAHOO.lang.JSON.stringify(myData);
// jsonStr now contains the string (without the leading comment slashes)
// {"puppies":[{"name":"Ashley","age":12,"NEWKEY":null},{"name":"Abby","age":9}]}

12/04/2007

always show/hide scrollbar in IE/Firefox

Men are greedy. IE always 有 vertical scrollbar 不管 document 的 size 是否超過了 canvas,所以我們想要 hide unnecessary vertical scrollbar

html{overflow:auto}

Always Show Vertical Scrollbar in Firefox [firefox] [css] [web]
html {overflow: scroll;} works but it also gives you a horizontal scroll bar.
html {overflow-y: scroll;} will give you just a vertical scroll bar, if that's what you are going for.

'overflow-x' and 'overflow-y' in Mozilla! - Anne’s Weblog
html {overflow: scroll;} works but it also gives you a horizontal scroll bar.
:root{overflow-y: scroll;}

layerX / layerY / offsetX / offsetY

Two Functions for Retreiving the Position of the Mouse Relative to the Current Element
MSDN Definition

event.offsetX: Sets or retrieves the x-coordinate of the mouse pointer's position relative to the object firing the event.

MDC Definition
event.layerX: Returns the horizontal coordinate of the event relative to the current layer.

// Get the X position of the mouse relative to the element target
// used in event object 'e'
function getElementX( e ) {
// Find the appropriate element offset
return ( e && e.layerX ) || window.event.offsetX;
}
// Get the Y position of the mouse relative to the element target
// used in event object 'e'
function getElementY( e ) {
// Find the appropriate element offset
return ( e && e.layerY ) || window.event.offsetY;
}

screen.width / screen.height / innerWidth / innerHeight / clientWidth / clientHeight / scrollTop / scrollLeft / scrollHeight / scrollWidth

要取得螢幕的resolution有簡單的cross-browser的作法:
MDC Definition

window.screen.height: Returns the height of the screen in pixels.

MSDN Definition
Retrieves the vertical resolution of the screen.

scrollHeight/scrollWidth
MDC Definition
DOM:element.scrollHeight: DHTML property that gets the height of the scroll view of an element; it includes the element padding but not its margin.

MSDN Definition
Retrieves the scrolling height of the object.

YUI:
   var scrollHeight = (document.compatMode != 'CSS1Compat') ? document.body.scrollHeight : document.documentElement.scrollHeight;


YUI's getDocumentHeight / getDocumentWidth
/**
* Returns the height of the document.
* @method getDocumentHeight
* @return {Int} The height of the actual document (which includes the body and its margin).
*/
getDocumentHeight: function() {
var scrollHeight = (document.compatMode != 'CSS1Compat') ? document.body.scrollHeight : document.documentElement.scrollHeight;

var h = Math.max(scrollHeight, Y.Dom.getViewportHeight());
return h;
},

/**
* Returns the width of the document.
* @method getDocumentWidth
* @return {Int} The width of the actual document (which includes the body and its margin).
*/
getDocumentWidth: function() {
var scrollWidth = (document.compatMode != 'CSS1Compat') ? document.body.scrollWidth : document.documentElement.scrollWidth;
var w = Math.max(scrollWidth, Y.Dom.getViewportWidth());
return w;
},

YUI's getViewportHeight / getViewportWidth
/**
* Returns the current height of the viewport.
* @method getViewportHeight
* @return {Int} The height of the viewable area of the page (excludes scrollbars).
*/
getViewportHeight: function() {
var height = self.innerHeight; // Safari, Opera
var mode = document.compatMode;

if ( (mode || isIE) && !isOpera ) { // IE, Gecko
height = (mode == 'CSS1Compat') ?
document.documentElement.clientHeight : // Standards
document.body.clientHeight; // Quirks
}

return height;
},

/**
* Returns the current width of the viewport.
* @method getViewportWidth
* @return {Int} The width of the viewable area of the page (excludes scrollbars).
*/

getViewportWidth: function() {
var width = self.innerWidth; // Safari
var mode = document.compatMode;

if (mode || isIE) { // IE, Gecko, Opera
width = (mode == 'CSS1Compat') ?
document.documentElement.clientWidth : // Standards
document.body.clientWidth; // Quirks
}
return width;
},

viewport code from PPK
var x,y;
if (self.innerHeight) // all except Explorer
{
x = self.innerWidth;
y = self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight)
// Explorer 6 Strict Mode
{
x = document.documentElement.clientWidth;
y = document.documentElement.clientHeight;
}
else if (document.body) // other Explorers
{
x = document.body.clientWidth;
y = document.body.clientHeight;
}


How much the page has scrolled.
var x,y;
if (self.pageYOffset) // all except Explorer
{
x = self.pageXOffset;
y = self.pageYOffset;
}
else if (document.documentElement && document.documentElement.scrollTop)
// Explorer 6 Strict
{
x = document.documentElement.scrollLeft;
y = document.documentElement.scrollTop;
}
else if (document.body) // all other Explorers
{
x = document.body.scrollLeft;
y = document.body.scrollTop;
}

Reference:
JavaScript - Window manipulation
Viewport introduction
Viewport - Properties

clientX / clientY / pageX / pageY

對一個 event 而言,我們常會用到的是 event 的(1)距離 document 左邊距離多少 / (2)距離 document 上面距離多少。
W3C Definition

clientX of type long, readonly
The horizontal coordinate at which the event occurred relative to the DOM implementation's client area.
clientY of type long, readonly
The vertical coordinate at which the event occurred relative to the DOM implementation's client area.

MDC Definition
event.clientX: Returns the horizontal coordinate within the application's client area at which the event occurred (as opposed to the coordinates within the page).
event.pageX: Returns the horizontal coordinate of the event relative to whole document.

DOM標準中,未明確定義 clientX 與 clientY 是相對於 canvas 還是 document,Firefox的作法是以 canvas 為準,並且另外定義以 document為準的 pageX 與 pageY。IE的 implement 是以 canvas 為準,所以需要加上捲軸的高度。其他的瀏覽器(Opera Konqueror iCab)


所以
by document: Mozilla Firefox (pageX/pageY),Opera, Konqueror, iCab
by canvas: Mozilla Firefox (clientX/clientY),IE


var ex, ey;
if(e.pageX && e.pageY){ // Mozilla Firefox
ex = e.pageX;
ey = e.pageY;
}
else if(e.clientx && e.clientY){
ex = e.clientx;
ey = e.clientY;
if(isIE){ // add scrollLeft, scrollTop to it.
ex += document.body.scrollLeft;
ey += document.body.scrollTop;
}
}

ref: PPK - JavaScript - Find position

offsetHeight / offsetWidth / offsetTop / offsetLeft

對一個 element 而言,我們常會用到的是 element 的(1)寬 / (2)高 / 與 (3)document 左邊距離多少 / (4)與 document 上面距離多少。
(1) elemenet 的寬就是 element.offsetWidth
(2) elemenet 的高就是 element.offsetHeight
(3) offsetTop 是 element 與 offsetParent 的距離。所以(3)的算法就是一直累加 offsetParent 的 offsetLeft,code 如下:

function findPosX(obj){
var curLeft = 0;
do{
curLeft += obj.offsetLeft;
} while(obj = obj.offsetParent);
}
return curLeft;

(4) 同理 offsetLeft 的算法為
function findPosX(obj){
var curTop = 0;
do{
curTop += obj.offsetTop;
} while(obj = obj.offsetParent);
}
return curTop;

12/03/2007

John Resig - Easy PDF Sharing

John Resig - Easy PDF Sharing - 用 Image Magic 把 pdf 轉成 png 在輸出在頁面上 - cool。下面中的 comment 有 slideshare 的人提到為什麼他們選擇用 swf 而不是 jpg/png 是因為 scaling 的問題。

SWFs scale very neatly and we can have players of different sizes from embeds to full screen.

source code

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);
}

editCSS for Internet Explorer

crisp's blog » Blog Archive » editCSS for Internet Explorer - concept - 底下的comment有提到accessibility toolbar,在CSS->Test Styles->選一個element,點edit style rule。
sourcecode

Now I was finally in business and so I present to you a simple concept of an editCSS feature in Internet Explorer (this link will only work in IE ofcourse…)

Not to mention that this is only a concept and has a lot of limitations: it doesn't work for stylesheets on another domain (since it uses XMLHttpRequest and thus is origin-bound), it doesn't really take into account media-types, the rules for alternate stylesheets are not really respected, it doesn't allow you to modify inline style-elements, it doesn't take into account @import or @media rules, it's a popup instead of a sidebar etcetera etcetera.

YUI Dimension api

getViewportHeight
Int getViewportHeight ( )
Returns the current height of the viewport.

Returns: Int
The height of the viewable area of the page (excludes scrollbars).



getRegion
Region | Array getRegion ( el )
Returns the region position of the given element. The element must be part of the DOM tree to have a region (display:none or elements not appended return false).

Parameters:
el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.

Returns: Region | Array
A Region or array of Region instances containing "top, left, bottom, right" member data.


getDocumentWidth
Int getDocumentWidth ( )
Returns the width of the document.

Returns: Int
The width of the actual document (which includes the body and its margin).


getDocumentScrollTop
Int getDocumentScrollTop ( document )
Returns the top scroll value of the document

Parameters:
document (optional) The document to get the scroll value of

Returns: Int
The amount that the document is scrolled to the top


getXY
Array getXY ( el )
Gets the current position of an element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).

Parameters:
el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements

Returns: Array
The XY position of the element(s)

gmail fragment identifiers

http://mail.google.com/mail/?shva=1#inbox/1169c4949d7598d6

#後面那一串就是 fragment identifiers, 可以讓 JavaScript keep 目前的 state, 像是目前使用者正在看的 tab, 不會因為使用者 refresh 之後就回到最初的狀態, 比較特別的是#後面還有inbox/, 看來可以好好利用一下。

Menu Editor :: Firefox Add-ons

Menu Editor :: Firefox Add-ons - 可有效去除context menu過長的毛病,尤其在過多的add-on都想佔據contenxt menu的情況下。

Rearrange or remove menuitems from the main context menu (right-click menu) and main menubar (File Edit View etc.)

IE fix

作者 coolfiretw (冷炎TM) 看板 Fuck
標題 Re: IE好像爛掉了
時間 Thu Nov 29 00:13:43 2007

※ 引述《whchu (風吹隨便倒...)》之銘言:
: IE用到一半,沒事就會出現ntdll.dll錯誤,然後就死掉。
: 拿winxp光碟片用修復裝一次也修不好。
: 幹!
試試看萬能解決法吧.....

重新註冊全部的DLL:
for %1 in (%windir%\system32\*.dll) do regsvr32.exe /s %1

反正一堆鳥問題,大部份都能解決.

12/02/2007

javascript pseudo-protocol HREF is harmful

http://kitty.2y.idv.tw/~chfang/test-revised.htm
odd problem about innerHTML & img under IE - comp.lang.javascript | Google 網上論壇

Executing a javascript pseudo-protocol HREF in IE browsers (at least up
to 6) convinces the browser that it about to navigate away from the
current page (as would be the normal consequence of following the HREF
of a link) and puts the browser into a 'waiting' stat in witch various
facilities stop working (or working in the previously expected way). One
of the more often observed symptoms is the browser failing to
load/display new images. This is usually reported as the unexpected
stopping of image swapping with rollovers, but any failure in an image
related operation after the execution of a javascript pseudo-protocol
HREF might be attributed to this.

Richard.

crisp's blog » Blog Archive » The useless javascript: pseudo-protocol

It comes down to this: when you use this in for instance an href-attribute you are most probably misusing an anchor-element for something that is not related to navigation. "You should not use a link for anything else but a link" - it's the basis of the web: links are for navigation and not for in-page behavior*. Got that?

Note the 'return false': this prevents a JS-capable client to actually start navigating to 'alternative.html'. That brings us to another problem with the javascript: pseudo-protocol, namely the fact that IE (at least up to version 6) enters a different 'state' when the href of a link is being followed no matter if it contains an actual link or a javascript function. This is most noticable when you have animated gifs on your page: when such a link is clicked they stop animating, and there are probably more problems that can arise from this 'state'-change in Internet Explorer. Wrapping your function-call in the void() operator doesn't change that either.

Re: A tag: href vs. onClick
update: 可以用< a id="next" href="#">
YUE.on('next', 'click', function(e){
doSomething();
YUE.stopEvent(e);
return fasle
})