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>

No comments :