今天要实现的功能是选项卡的自动轮换,我原来用Prototype.js写了一个简单的选项卡,并用类
继承的方式完成了此项功能。
Mootools.js一样能轻松实现类的继承,Mootools.js实现类的继承是通过Class的Extends属性完成的。
自动轮换功能的思路是:通过setInterVal函数来调用自动切换选项卡函数,并从用户体验的角度考虑,实现当鼠标移到选项卡上时停止轮换,离开后继续。
下面代码中的AutoTabs类,就是通过继承上节完成的Tabs类来实现了自动轮换功能,通过startAuto()的实例方法来进行调用。
虽然能用继承的方式完成功能,但是并不是因为有继承才叫好的面向对象,面向对象编程思想还有一条原则是,多用组合,少用继承。
因此,我将代码进行再次改写,仍然是通过implement方法将自动轮换功能添加到Tabs类里,一样是通过startAuto()方法调用,这样完成的代码将更加灵活。
自动轮换示例页
AutoTabs类:
Code
1 var AutoTabs = new Class({
2
3 Extends:Tabs,
4
5 options:{
6 autoInterval:5
7 },
8
9 startAuto:function(){
10 this.attachAuto();
11 this.start();
12 },
13
14 attachAuto:function(){
15 this.bindOver = this.stop.bind(this);
16 this.bindOut = this.start.bind(this);
17 this.tabs.getParent().addEvents({
18 'mouseenter':this.bindOver,
19 'mouseleave':this.bindOut
20 });
21 this.sections.getParent().addEvents({
22 'mouseenter':this.bindOver,
23 'mouseleave':this.bindOut
24 });
25 },
26
27 start:function(){
28 this.autoId = this.autoToggle.periodical(this.options.autoInterval*1000,this);
29 },
30
31 stop:function(){
32 $clear(this.autoId);
33 },
34
35 autoToggle:function(){
36 this.numNext = this.current + 1;
37 this.numNext = this.numNext >= this.sectionsLength ? 0 : this.numNext;
38 this.toggleSection(this.numNext);
39 }
40 });
将自动轮换功能做为独立方法implement到Tabs类里:
Code
1 /**
2 * implement auto change Tab method to Tabs class
3 */
4 Tabs.implement({
5 startAuto:function(){
6 this.attachAuto();
7 this.start();
8 },
9
10 attachAuto:function(){
11 this.bindOver = this.stop.bind(this);
12 this.bindOut = this.start.bind(this);
13 this.tabs.getParent().addEvents({
14 'mouseenter':this.bindOver,
15 'mouseleave':this.bindOut
16 });
17 this.sections.getParent().addEvents({
18 'mouseenter':this.bindOver,
19 'mouseleave':this.bindOut
20 });
21 },
22
23 start:function(){
24 this.autoId = this.autoToggle.periodical(this.options.autoInterval*1000,this);
25 },
26
27 stop:function(){
28 $clear(this.autoId);
29 },
30
31 autoToggle:function(){
32 this.numNext = this.current + 1;
33 this.numNext = this.numNext >= this.sectionsLength ? 0 : this.numNext;
34 this.toggleSection(this.numNext);
35 }
36 });