在这一节里,我将继续对Tabs类进行扩展,加上动态添加和删除选项卡的功能。
这个功能是我在看到126邮箱里用选项卡来查看邮件后,想到在Tabs类也实现相应的功能
思路如下:
添加新选项卡函数有四个参数,分别是新加标签的文本,新加内容的文本,新加选项卡的位置以及在选项标签上加入删除的按钮。
用传入的参数分别建立Element片段,加入到选项卡标签数组及选项卡内容数组,并将Element片段插入到DOM中,同时将选项卡标签事件绑定到新加标签,最后显示新加的内容。
而删除函数则是添加新选项卡函数的反过程。
我还在这两个函数里分别发布了两个自定义事件onAdd和onRemove,能更方便的实现自定义函数。
示例页
最终代码是在上节完成的代码后面,再使用implement方法在不改动原有类的情况下加上了新加了两个方法。
Code
1 /**
2 * implement two methods to Tabs class: addSection & removeSection
3 */
4 Tabs.implement({
5 addSection:function(newTabHtml,newSectionHtml,pos,delA){
6 var length = this.sectionsLength;
7 pos = $pick(pos, length).limit(0, length);
8
9 pos2 = pos==length?pos-1:pos;
10 var oldTab = this.tabs[pos2];
11 var oldSection = this.sections[pos2];
12
13 var posMethod = pos == length ? 'after':'before';
14 var newTab = oldTab.clone().set('html',newTabHtml).inject(oldTab,posMethod);
15 var newSection = oldSection.clone().set('html',newSectionHtml).setStyle('display','none').inject(oldSection,posMethod);
16
17 this.tabs.splice(pos,0,newTab)
18 this.sections.splice(pos,0,newSection)
19 this.sectionsLength++;
20
21 if(pos<=this.current){
22 this.current++;
23 }
24
25 var delA= newTab.getElement('a.'+delA);
26 if (delA){
27 delA.addEvent('click',this.removeSection.bindWithEvent(this,[newTab,delA]));
28 }
29
30 newTab.addEvent(this.options.mouseEvent,this.tabEvent.bindWithEvent(this,newTab));
31 this.toggleSection(pos);
32
33 this.fireEvent('onAdd',[newTab,newSection]);
34 },
35
36 removeSection:function(e,tab,delA){
37 e.stop();
38 delA.removeEvents();
39 var index = this.tabs.indexOf(tab);
40
41 this.tabs.splice(index,1);
42 var section = this.sections.splice(index,1)[0];
43 this.sectionsLength--;
44
45 tab.removeEvents();
46 tab.destroy();
47 section.destroy();
48
49 if(this.current==index){
50 this.current = (index-1).limit(0,this.sectionsLength);
51 this.showSection(this.current);
52 }
53 this.current--;
54 this.current = this.current.limit(0,this.sectionsLength);
55 this.fireEvent('onRemove',index);
56 }
57 });