把代码变成一个类

时间:2011-06-17 05:29:11

标签: javascript oop class mootools

var tabs = $('ul li a.class');
tabs.addEvent('click', function(){
tabs.removeClass('active');
this.addClass('active');
});

var tabs = new Fx.Scroll('contents', {
duration: 2000
});

var scroller = $('.class');
scrollTab.addEvent('click',function(e){
el_id = this.id.split('_'); 
slide_el = 'myTab_' + el_id[1];
tbas.toElement(slide_el);
}); 

我想知道如何将这段代码转换为模块化的mootools类,我可以在其他页面上重复使用。

我有一个基本的想法,但似乎没有工作

var class = new Class({
   Implements: [Options, events],
   options:{
    duration: 1500,
    tabs: $(ul li a.class)
   },
  Initialize: function(options){
  this.setOPtions(options);
},
method1:{
/////
},
method2:{
/////
},

});

我知道我必须有两个方法,一个用于制作标签开关的颜色,一个用于制作标签的功能....你能帮我做这个工作吗?谢谢

1 个答案:

答案 0 :(得分:1)

你的代码中有一些错误,你需要学习一些mootools类:):

var myClass = new Class({ // you can't use var class<- reserved word

    Implements: [Options, Events], //Events uppercase, and, are going to use it?

    options:{
        duration: 1500
       /*,tabs: $('ul li a.class') see initialize, tabs as a parameter */ 
    },

    initialize: function(tabs, scrollers, options){

        this.setOptions(options); //u had a typo in setOptions

        this.tabs = tabs;

        this.scrollers = scrollers;

        this.method1(); //i.e. build tabs

        this.scrollables = new Fx.Scroll(this.options.contentToScroll, {
            duration: this.options.duration
        });

        this.method2(); //i.e. build scrollers

    },

    method1 : function(){ //a 'method' is a function

        var self = this;

        this.tabs.addEvent('click', function(){
            self.tabs.removeClass('active'); //note 'self' that references to the instantiated and 'running' 'myClass' object
            this.addClass('active');
        });

    },

    method2 : function(){ // 'method' = function

        var self = this;

        this.scrollers.addEvent('click',function(e){
            el_id = this.id.split('_'); 
            slide_el = 'myTab_' + el_id[1];
            self.tabs.toElement(slide_el);
        }); 

    }

    /*, otherPublicMethod : function(){} */

});

//to instantiate a 'myClass'

var myClassInstance = new myClass(
    $('ul li a.class') /* tabs elems*/, 
    $('.class') /*scroller elems*/, 
    { duration : 15000, contentToScroll : $('content') } /* options */
);

值得一读=&gt; http://ryanflorence.com/mootools-class/http://mootorial.com/wiki/mootorial/09-howtowriteamootoolsclass