Showing posts with label Library. Show all posts
Showing posts with label Library. Show all posts

Wednesday, August 27, 2008

My drag drop library example


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My Drag and Drop Example</title>
<script type="text/javascript" src="/lib/prototype.js"></script>
<script type="text/javascript" src="/lib/mydragdrop.js"></script>

<style type="text/css">
#dragDiv, #dragDiv2 {
*width: 150px;
min-width: 150px;
border: #333 1px solid;
min-height: 150px;
float: left;
}
#dropDiv {
*width: 150px;
min-width: 150px;
border: #333 1px solid;
min-height: 150px;
margin-left: 20px;
float: left;
}
.hoverActive {
background-color: #ffc;
}
img {
vertical-align: middle;
}
</style>
</head>
<body>
<div id="dragDiv">
<img id="img1" src="/images/puzzle1.jpg"/><img id="img2" src="/images/puzzle2.jpg"/><img id="img3" src="/images/puzzle3.jpg"/>
</div>
<div id="dragDiv2">
<img id="img4" src="/images/puzzle4.jpg"/>
</div>

<div id="dropDiv">
</div>
<script type="text/javascript">
window.onload = function() {
new Drag('img1', {revert: false});
new Drag('img2', {revert: true});
new Drag('img3', {revert: true});
new Drag('img4', {revert: true});
Drop.add('dropDiv', {hoverclass: 'hoverActive', containers: ["dragDiv"],
onDrop: function(drag, drop) {
drag.style.left = "";
drag.style.top = "";
drop.style.borderColor = "#000";
drop.style.borderWidth = "thin";
if (drop.lastChild.nodeType == 3) drop.removeChild(drop.lastChild);
drop.appendChild(drag);
},
onHover: function(drag, drop){
drop.style.borderColor = "#886";
drop.style.borderWidth = "thick";
}
});
Drop.add('dragDiv', {hoverclass: 'hoverActive',
onDrop: function(drag, drop) {
drag.style.left = "";
drag.style.top = "";
if (drop.lastChild.nodeType == 3) drop.removeChild(drop.lastChild);
drop.appendChild(drag);
}
});
}
</script>
</body>
</html>

Here is mydragdrop.js source

MyDragDrop javascript library v0.1 based prototype 1.6.1


// MyDragDrop 0.1 - based Prototype and imitate script.aculo.us dragdrop.js

DragController = {
drags: [],
dragging: false,
currentDrag: null,
register: function(drag) {
if(this.drags.length == 0) {
Event.observe(document, "mouseup", this.endDrag.bindAsEventListener(this));
Event.observe(document, "mousemove", this.updateDrag.bindAsEventListener(this));
Event.observe(document, "keypress", this.keyPress.bindAsEventListener(this));
}
this.drags.push(drag);
},
updateDrag: function(event) {
this.currentDrag && this.currentDrag.updateDrag(event);
},
endDrag: function(event) {
this.currentDrag && this.currentDrag.endDrag(event, true);
},
keyPress: function(event) {
this.currentDrag && this.currentDrag.keyPress(event);
}
};

Drag = Class.create({
initialize: function(element) {
var defaults = {
handle: false,
zindex: 1000,
revert: false,
ghosting: false,
opacity: 0.0
};
this.element = $(element);
this.options = Object.extend(defaults, arguments[1] || {});
DragController.register(element);
// fix IE position problem.
if(Prototype.Browser.IE) {
var position = this.element.style.position;
if (position == 'static' || !position) this.element.style.position = 'relative';
}
Event.observe(element, "mousedown", this.startDrag.bindAsEventListener(this));
},
startDrag: function(event) {
if(Event.isLeftClick(event)) {
this.relativePosition = [this.element.style.left, this.element.style.top];
this.clone = this.element.cloneNode(true);
this.positionAbsolutize();
this.element.parentNode.insertBefore(this.clone, this.element);
this.originalOpacity = this.element.getOpacity();
this.element.setOpacity(0.7);
if(!this.options.ghosting) {
this.clone.setOpacity(this.options.opacity);
}
this.element.style.zIndex = this.options.zindex;
this.element.style.cursor = "move";
// hack safari inline element shadow problem.
// this negative effect is block-level element display inline
if (Prototype.Browser.WebKit && this.element.style.display != "block" &&
["a", "b", "i", "q", "s", "em", "big", "sup", "sub", "abbr", "code", "cite", "span", "quote", "small", "strike", "strong"].include(this.element.tagName.toLowerCase()))
this.element.style.display = "inline-block";
this.startPointer = [Event.pointerX(event), Event.pointerY(event)];
this.positionedOffset = [this.element.offsetLeft, this.element.offsetTop];
DragController.dragging = true;
DragController.currentDrag = this;
}
Event.stop(event);
},
updateDrag: function(event) {
if (DragController.dragging) {
var currentPointer = [Event.pointerX(event), Event.pointerY(event)];
this.element.style.left = (currentPointer[0] - this.startPointer[0] + this.positionedOffset[0] - parseInt(this.element.style.marginLeft || 0)) + "px";
this.element.style.top = (currentPointer[1] - this.startPointer[1] + this.positionedOffset[1] - parseInt(this.element.style.marginTop || 0)) + "px";
Drop.show(currentPointer, this.element);
}
Event.stop(event);
},
endDrag: function(event, success) {
if (DragController.dragging) {
DragController.dragging = false;
DragController.currentDrag = null;
this.element.setOpacity(this.originalOpacity);
var currentPointer = [Event.pointerX(event), Event.pointerY(event)];
this.element.style.position = "relative";
this.element.style.left = (currentPointer[0] - this.startPointer[0] + parseInt(this.relativePosition[0] || 0)) + "px";
this.element.style.top = (currentPointer[1] - this.startPointer[1] + parseInt(this.relativePosition[1] || 0)) + "px";
this.clone.remove(); // clone remove must before Drop event fire because clone will hold position
this.clone = null;
if(!success) {
this.revertDrag(event);
} else {
var dropped;
if (Drop.lastDrop) {
Drop.removeHoverClass();
dropped = Drop.fire(event, this.element, Drop.lastDrop);
}
if (!dropped && this.options.revert)
this.revertDrag(event);
}
}
Event.stop(event);
},
keyPress: function(event) {
if(event.keyCode != Event.KEY_ESC) return;
this.endDrag(event, false);
Event.stop(event);
},
revertDrag: function(event) {
this.element.style.left = this.relativePosition[0];
this.element.style.top = this.relativePosition[1];
},
positionAbsolutize: function() {
if (this.element.getStyle('position') == 'absolute') return;
var offsets = [this.element.offsetLeft, this.element.offsetTop];
// offsetLeft include this element's marginLeft value.
var left = offsets[0] - parseInt(this.element.style.marginLeft || 0);
var top = offsets[1] - parseInt(this.element.style.marginTop || 0);
this.element.style.position = 'absolute';
this.element.style.top = top + 'px';
this.element.style.left = left + 'px';
}
});

var Drop = {
drops: [],
lastDrop: null,
add: function(element) {
var drop = Object.extend({
hoverClass: null
}, arguments[1] || {});
drop.element = $(element);
this.drops.push(drop);
},
isContained: function(drag, drop) {
var container = drag.parentNode;
return drop.containers.detect(function(c) {return $(c) == container });
},
dragHovered: function(pointer, drag, drop) {
return ((drop.element != drag) && ((!drop.containers) || this.isContained(drag, drop)) &&
Position.within(drop.element, pointer[0], pointer[1]));
},
removeHoverClass: function() {
Element.removeClassName(Drop.lastDrop.element, Drop.lastDrop.hoverclass);
},
show: function(pointer, drag) {
if(!this.drops.length) return;
var hovered = false;
this.drops.each(function(drop) {
if(Drop.dragHovered(pointer, drag, drop)) {
hovered = true;
Drop.lastDrop = drop;
Element.addClassName(drop.element, drop.hoverclass);
if(drop.onHover) drop.onHover(drag, drop.element);
}
});
if (Drop.lastDrop && !hovered)
this.removeHoverClass();
},
fire: function(event, drag, drop) {
if (drop && this.dragHovered([Event.pointerX(event), Event.pointerY(event)], drag, drop)) {
if(drop.onDrop) drop.onDrop(drag, drop.element, event);
return true;
}
}
}

example: http://yuweijun.blogspot.com/2008/08/my-drag-drop-library-example.html

Thursday, November 08, 2007

Rails development environment problem

在开发模式下,Rails的Models里的文件修改后会自动重载入,但是Models里require进来的Ruby lib和Rails lib下的文件有所修改是不会自动重载入的,必须需要重启Rails应该。

Thursday, October 18, 2007

Usage of Ruby parseexcel lib

gem包安装后的README文件有个实例简单说明了这个lib的使用方法,gem包没有安装doc


#!/usr/bin/env ruby

require 'parseexcel'

# your first step is always reading in the file.
# that gives you a workbook-object, which has one or more worksheets,
# just like in Excel you have the possibility of multiple worksheets.
workbook = Spreadsheet::ParseExcel.parse(path_to_file)

# usually, you want the first worksheet:
worksheet = workbook.worksheet(0)

# now you can either iterate over all rows, skipping the first number of
# rows (in case you know they just contain column headers)
skip = 2
worksheet.each(skip) { |row|
# a row is actually just an Array of Cells..
first_cell = row.at(0)

# how you get data out of the cell depends on what datatype you
# expect:

# if you expect a String, you can pass an encoding and (iconv
# required) the content of the cell will be converted.
str = row.at(1).to_s('latin1')

# if you expect a Float:
float = row.at(2).to_f

# if you expect an Integer:
int = row.at(3).to_i

# if you expect a Date:
date = row.at(4).date

# ParseExcel makes a guess at what Datatype a cell has. At the moment,
# possible values are: :date, :numeric, :text
celltype = first_cell.type
}

# if you know exactly which row your data resides in, you may just
# retrieve that row, which is again simply an Array of Cells
row = worksheet.row(26)

Sunday, August 05, 2007

prototype javascript library 1.5.1 examples


<script type="text/javascript" charset="utf-8">
function doc (argument) {
document.write(argument);
document.write("<br />\n");
}

doc(Prototype.Version);
doc(document.evaluate);
doc(!!document.evaluate);

doc(Prototype.emptyFunction);
doc(Prototype.K('test'));

var reg = new RegExp(Prototype.ScriptFragment);
doc(reg);
doc(reg.source);

var script = '<script type="text/javascript" charset="utf-8">var x;<\/script>';

var rs = reg.exec(script);
doc(rs.length);
</script>

prototype javascript library Template pattern example


<script type="text/javascript" charset="utf-8">
function doc(argument) {
document.write("<p>\n");
document.write(argument);
document.write("</p>\n");
}

function printCart(){
//creating a sample cart
var cart = new Object();
cart.items = [ ];
//putting some sample items in the cart
cart.items.push({product: 'Book 123', price: 24.50, quantity: 1});
cart.items.push({product: 'Set of Pens', price: 5.44, quantity: 3});
cart.items.push({product: 'Gift Card', price: 10.00, quantity: 4});
//here we create our template for formatting each item
var itemFormat = new Template('You are ordering #{quantity} units of #{product} at $#{price} each.');
var formatted = '';
for(var i=0; i<cart.items.length; i++){
var cartItem = cart.items[i];
formatted += itemFormat.evaluate(cartItem) + '<br/>\n';
}

doc(formatted);
}
printCart();

var oldStr = 'testStringGsubAndTemplate';
var oldPattern = /Str(.*?)(G.*?)And/;
var regNoReplace = ' {1} + {2} ';
var regAllReplace = ' #{1} + #{2} ';
var regPartReplace = ' \\#{1} + #{2} ';

var rnr = oldStr.gsub(oldPattern, regNoReplace);
doc(rnr);
var rar = oldStr.gsub(oldPattern, regAllReplace);
doc(rar);
var rpr = oldStr.gsub(oldPattern, regPartReplace);
doc(rpr);
//alert(regNoReplace.match(Template.Pattern)); // return null, will not perform replacement function(match) {var before... }
var tg = (new Template(regNoReplace)).evaluate(oldStr.match(oldPattern));
doc(tg);
//alert(regPartReplace.match(Template.Pattern)); // return match object, will perform replacement function(match) {return template.ev....}
var tgp = (new Template(regPartReplace)).evaluate(oldStr.match(oldPattern));
doc(tgp);
</script>

prototype javascript library Enumerable.each example


<script type="text/javascript" charset="utf-8">
function doc(argument) {
document.write(argument);
document.write("<br />\n");
}
var Enumerable = {
each: function(iterator) {
var index = 0;
try {
this._each(function(value) {
alert(iterator); // then alert function(i){doc(i);} every time
iterator(value, index++);
});
} catch (e) {
if (e != $break) throw e;
}
return this;
}
};
Object.extend(Array.prototype, {
_each: function(iterator) {
for (var i = 0, length = this.length; i < length; i++){
alert(iterator); // first alert function(value) {alert(iterator); iterater(value, index++);} every time
iterator(this[i]); // through here revoke follow alert
}
}
});
Object.extend(Array.prototype, Enumerable);

var a = [1, 2, 3, 4];
a.each(function (i) {
doc(i);
});
/*
var t = a.all(function (i) {
return i.constructor == Number;
})
doc('all() = ' + t); // true
var f = a.all(function (i) {
return i % 2 == 0;
})
doc('all() = ' + f); // false

var y = a.any(function (i) {
return i % 2 == 0;
})
doc('any() = ' + y); // true

var m = a.collect(function (i) {
return i * 10;
}); // Array.map
doc('inspect() = ' + m.inspect());

var fa = a.findAll(function (i){
return i % 2 == 0;
});
doc('findAll() = ' + fa.inspect());

var str = ['test1', 'test2', 'test3', 'text1', 'text2', 'text3'];
var sg = str.grep(/test/i);
doc('grep() = ' + sg.inspect());

var inc = str.include('test1');
doc('include() = ' + inc);

var sum = a.inject(0, function (s, i) {
return s + i;
});
doc('sum = ' + sum);
doc('max = ' + a.max());
doc('min = ' + a.min());
doc('first = ' + a.first());
doc('last = ' + a.last());

a = a.concat(2, 4);
doc('a = ' + a.inspect());
doc('uniq() = ' + a.uniq().inspect());*/
</script>

prototype javascript library ajax example


<div id="ajax_div">
use ajax to update it!
</div>
<br/>
<div id="ajax_failure">
if evalScript set false, sayHi is not defined!
</div>

<input type="button" name="button_ajax" value="ajax update div" id="button_ajax" />

<script type="text/javascript" charset="utf-8">
function doc(argument) {
document.write("<p>\n");
document.write(argument);
document.write("</p>\n");
}
var url = '/prototype/ajax_eval_script';
var options = {
method: 'get',
evalScripts: true,
parameters: 'id=1',
insertion: Insertion.Top
}

//new Ajax.Updater('ajax_div', url, options);
//new Ajax.Request(url, {onComplete: function (req) { alert(req.responseText); }});
var ajax = new Ajax.Request();
doc('ajax.transport type is ' + ajax.transport); //ajax.transport = Ajax.getTransport();
new Ajax.Updater({success: 'ajax_div', failure: 'ajax_failure'}, url, options);

ajax.setOptions(Object.extend(options, {onComplete: function(req) {
$('ajax_div').innerHTML = req + "<br/>\n" +
"req == ajax.transport is " + (req == ajax.transport) + "<br/>\n" +
"Server is " + req.getResponseHeader('Server') + "<br/>\n" +
"ajax request status is " + ajax.transport.status + "<br/>\n";
}
}));
$('button_ajax').onclick = function (event) { ajax.request('/prototype/ajax_eval_script'); };
</script>

/prototype/ajax_eval_script

<script language="javascript" type="text/javascript">
//function sayHi(){ // do nothing, function is not generated in runtime
//var sayHi = function(){ // not use the "var" keyword
sayHi = function(){
alert('Hi');
}
</script>

<input type="button" value="Click Me" onclick="sayHi()"/>
Note that in the previous example we did not use the var keyword to declare the variable. Doing so would have created a function object that would be local to the script block (at least in IE and FireFox). Without the var keyword the function object is scoped to the window, which is our intent.

prototype javascript library Selector example


<ul id="fruits">
<li id="apples">
<h3 title="yummy!" id="hid">Apples</h3>
<ul id="list-of-apples">
<li id="golden-delicious" title="yummy!" >Golden Delicious</li>
<li id="mutsu" title="yummy!">Mutsu</li>
<li id="mcintosh">McIntosh</li>
<li id="ida-red">Ida Red</li>
</ul>
<p id="saying">An apple a day keeps the doctor away.</p>
</li>
</ul>
<script type="text/javascript" charset="utf-8">
function doc(argument) {
document.write("<br>\n");
document.write(argument);
document.write("</br>\n");
}

$$('p', 'h3').each(function (i) {
doc(i.tagName.toLowerCase() + ':' + i.id);
});
doc('======================================================================');
// $$(exps) == document.getElementsBySelector(exps) == Selector.findChildElements(document, $A(exps))
Selector.findChildElements(document, ['p', 'h3']).each(function (i) {
doc(i.tagName.toLowerCase() + ':' + i.id);
});
doc('======================================================================');
doc(Selector.matchElements($('apples', 'saying'), 'p').length);
Selector.matchElements($('apples', 'saying'), 'p').each(function (i) {
doc(i.tagName.toLowerCase() + ':' + i.id);
});
doc(Selector.findElement($('apples', 'golden-delicious', 'mutsu', 'mcintosh', 'ida-red'), 'li', 1).id);
doc('======================================================================');
doc($('apples').match('li'));
doc($('apples').match('p'));
var s = new Selector('p');
doc(s.match($('saying')));
doc('======================================================================');
var l = new Selector('li p');
l.findElements($('fruits')).each(function (i) {
doc(i.tagName.toLowerCase() + ':' + i.id);
});
var l = new Selector('ul li');
l.findElements($('fruits')).each(function (i) {
doc(i.tagName.toLowerCase() + ':' + i.id);
});
doc('======================================================================');
$('apples').getElementsBySelector('[title="yummy!"]').each(function (y) {
doc(y.tagName.toLowerCase());
});
doc('======================================================================');
$('apples').getElementsBySelector( 'p#saying', 'li[title="yummy!"]').each(function (c) {
doc(c.tagName.toLowerCase());
});
doc('======================================================================');
doc($('apples').getElementsBySelector('[title="disgusting!"]').length);
doc('======================================================================');
doc($('apples').getElementsBySelector('[id^="m"]').length);
$('apples').getElementsBySelector('[id^="m"]').each(function (i) {
doc(i.tagName.toLowerCase() + ':' + i.id);
});

</script>

Friday, August 03, 2007

prototype javascript library Function extends example


<script type="text/javascript" src="prototype.js" charset="utf-8"></script>

<input type="checkbox" id="myChk" value="1"/> Test Function.prototype.bindAsEventListener

<input type="button" id="myBut1" value="bind element test" onclick="doc.bind(this)('arg1', 'arg2');"/> Test Function.prototype.bind

<input type="button" id="myBut2" value="bind window test" onclick="doc.bind(self)('arg1');"/> Test Function.prototype.bind

<script type="text/javascript" charset="utf-8">
function doc(){
// this 根据调用它的对象不同而不同,可以是element对象, 也可以是当前window对象
alert([this].concat($A(arguments)).inspect());
}

//declaring the class
var CheckboxWatcher = Class.create();
//defining the rest of the class implementation
CheckboxWatcher.prototype = {
initialize: function(chkBox, message) {
this.chkBox = $(chkBox);
this.message = message;
//this.chkBox.onclick
// = this.showMessage.bindAsEventListener(this, ' other extraInfo')
// => function(event) { return __method.apply(object, [event || window.event].concat(args));}

//将showMessage方法做为this object的方法来调用并返回showMessage方法的结果
//既然是将showMessage做为this object的方法来调用,那showMessage中的this是指向当前调用它的object(即为CheckboxWatcher的实例对象,如watcher)。
//this.chkBox.onclick = this.showMessage.apply(this, ['none event', ' other extraInfo']);
//assigning our method to the event
this.chkBox.onclick = this.showMessage.bindAsEventListener(this, ' other extraInfo');
},

showMessage: function(evt, extraInfo) {
//this是指向watcher这个实例对象的
//showMessage这个方法一般是不会从外部调用的
alert(this.message + ' (' + evt + ')' + extraInfo);
},

bindExample: function() {
alert(this.message + "\n" + $A(arguments).inspect);
}
};

var watcher = new CheckboxWatcher('myChk', 'Changed');
</script>

Thursday, April 05, 2007

javascript templating library


<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
<script type="text/javascript"
src="http://mjtemplate.org/dist/latest/mjt.js"></script>
</head>
<body onload="mjt.run('top')">
<div id="top" style="display:none">
The group behind Freebase have released MTJ, the templating library they created for their own use:

Mjt makes it very simple to take data from a web service and format it in a browser, with no server support. The templates are hosted and delivered as static HTML, and they are compiled and applied entirely in Javascript.

Mjt is particularly useful with services that return JSON values and accept a callback= parameter, such as the Freebase service and the Yahoo JSON API. With these services you can use mjt to build "mash-ups" that incorporate data from services on multiple hosts.
<!-- the template lives inside this div element => running mjt version 0.3 -->
running mjt version $mjt.VERSION

</div>
</body></html>