js封装,类似java、c#中的事件委托。写出来测试不正确,急求大师们来指导一下。
废话少说,直接贴代码:
- JScript code
person.js文件中的代码 var person = function (name) { var name = name; this.onRun; this.run = function () { onRun(name); } }
- HTML code
<html> <head> <script type="text/javascript" src="jquery-1.7.2.min.js"></script> <script type="text/javascript" src="person.js"></script> <script type="text/javascript"> function run(name) { alert(name + "在奔跑"); } var person; $(documen).ready(function () { person = new person("刘德华"); person.onRun = run; //这里绑定事件方法,应该这么说 person.run(); //这里会触发事件 }); </script> </head> <body> <div>test page</div> </body> </html>
------解决方案--------------------
var person = function (name) {
this.name = name;
this.onRun = function(){};
this.run = function(){this.onRun(name)}
}
function run(name) {
alert(name + "在奔跑");
}
var person = new person("刘德华");
person.onRun = run;
person.run(person.name);
------解决方案--------------------
BTW:貌似java、c#中也不是那样干的吧^O^
------解决方案--------------------
有错,更正:
- JScript code
var person = function (name) { this.name = name; this.onRun = function(){}; this.run = function(){this.onRun(this.name)} } function run(name) { alert(name + "在奔跑"); } var person = new person("刘德华"); person.onRun = run; person.run();
------解决方案--------------------
把方法传递进去就行:
- JScript code
var person = function (name) { this.name = name; this.run = function(method){method.apply(this)} } var person = new person("刘德华"); person.run(function(name) { alert(this.name + "在奔跑"); });
------解决方案--------------------
这不更简单吗?
- JScript code
var person = function (name) { this.name = name; this.onRun = function() {}; this.run = function(){ this.onRun() } } function run(name) { alert(this.name + "在奔跑"); } var person = new person("刘德华"); person.onRun = run; person.run();
------解决方案--------------------
this.run = function () {
//onRun(name); 错误在这 没加 this
this.onRun(name);
}
另外下面document也拼错了
------解决方案--------------------
- JScript code
var person = function (name) { this.name = name; this.onRun = function() {}; this.run = function(){ this.onRun() } } function runX(name) { alert(this.name + "在奔跑"); } function runY(name) { alert(this.name + "在睡觉"); } var personQ = new person("刘德华"); personQ.onRun = runX; personQ.run(); personQ.onRun = runY; personQ.run(); var personR = new person("周星驰"); personR.onRun = runX; personR.run(); personR.onRun = runY; personR.run();