seajs的一次尝试

  SeaJS是一个遵循CommonJS规范的JavaScript模块加载框架,可以实现JavaScript的模块化开发及加载机制。

  与jQuery等JavaScript框架不同,SeaJS不会扩展封装语言特性,而只是实现JavaScript的模块化及按模块加载。

  SeaJS的主要目的是令JavaScript开发模块化并可以轻松愉悦进行加载,将前端工程师从繁重的JavaScript文件及对象依赖处理中解放出来,可以专注于代码本身的逻辑。

  SeaJS可以与jQuery这类框架完美集成。使用SeaJS可以提高JavaScript代码的可读性和清晰度,解决目前JavaScript编程中普遍存在的依赖关系混乱和代码纠缠等问题,方便代码的编写和维护。

    特点:

  1、SeaJS 遵循CMD规范,可以像Node.js一般书写模块代码。

  2、依赖的自动加载、配置的简洁清晰。

 

  开始第一次尝试

  在html代码加载seajs lib

  

    <script src="sea.js"></script>
    <script>
        seajs.use(["common","index"]);
    </script>

 

  如上js中,需要依赖common和index这两个js文件。

  现构建common.js 和index.js模块

  

/**
 * @name 基础js
 * @description 整站基础js模块
 * @date 2014-12-21
 * @version $V1.0$
 */
define(function(require, exports, module) {
    //引入依赖函数
    require('jquery');
    //--------------------------------------------------【切换栅格模式】
    $(window).bind("load resize", function() {
        if (document.documentElement.clientWidth > 1230) {
            $("body").addClass("full");
            $(".no_full").show();
        } else {
            $("body").removeClass("full");
            $(".no_full").hide();
        }
    });
    //--------------------------------------------------【返回顶部】
    require('module/roll_to');
    var iHeight=$(window).height();
    $(window).bind('scroll', function(event) {
        if ($(window).scrollTop() >= iHeight / 2) {
            $("#quickfloat .top").removeClass('js_hide');
        } else {
            $("#quickfloat .top").addClass('js_hide');
        }
    });
    $("#quickfloat .top").rollTo({
        sSpeed: 500
    });
    //--------------------------------------------------【IE6提示升级跳转】
    if ($.browser.version <= 6) {
        window.location.href = "http://localhost/ie6prompt.html";
    }
});

  而在index.js中使用了animate,data_format等,

define(function(require, exports, module) {
    require('jquery');

    var aniamte=require('animate.js');

    var data_format=require('data_format.js');


    //doing something;            
}

  在common.js 和index.js中分别依赖了jquery、roll_to.js、data_format.js animate.js,按照CMD标准分别编写这几个模块。

  1、roll_to.js模块  

/**
 * @name rollTo滚动跳转
 * @description 功能模块
 */
define(function(require, exports, module) {
    //引入依赖函数
    require('jquery');
    $.fn.extend({
        rollTo: function(value) {
            var o = {
                oFinish: "body", //要滚动到的元素
                sSpeed: "0", //滚动速度
                bMonitor: false, //是否楼层监听
                sClass: "current", //楼层监听时需要添加的样式
                fnAdditional: "" //追加方法
            }
            o = $.extend(o, value);
            var oThis = $(this),
                targetOffset = $(o.oFinish).offset().top;
            oThis.click(function() {
                $("html,body").stop(true, true).animate({
                    scrollTop: targetOffset
                }, o.sSpeed);
                o.sSpeed == 0 && $("body").stop(true, true);
                o.fnAdditional && o.fnAdditional();
            });
            if (o.bMonitor) {
                $(window).bind("scroll load", function(event) {
                    if ($(this).scrollTop() >= targetOffset) {
                        oThis.addClass(o.sClass).siblings().removeClass(o.sClass);
                    }
                });
            }
            return $(this);
        }
    });
});

2、data_format.js模块

/**
 * @name date格式化
 * @description 功能模块
 */
define(function(require, exports, module) {
    var TimeFormat = function() {
        /**
         * 日期格式化     
         * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符
         * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
         * eg:
         * var obj=new TimeFormat();
         * obj.format(<dateStr>,"yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
         * obj.format(<dateStr>,"yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04
         * obj.format(<dateStr>,"yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
         * obj.format(<dateStr>,"yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
         * obj.format(<dateStr>,"yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
         * ps:
         * <dateStr>为用户需要格式化的date字符串,可以是毫秒也可以是日期格式,例如"86400000"或"2014/07/07"等。用于new Date()
         */
        this.format = function(dateVal, fmt) {
            var date = new Date(dateVal);
            var o = {
                "M+": date.getMonth() + 1, //月份           
                "d+": date.getDate(), //
                "h+": date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, //小时           
                "H+": date.getHours(), //小时           
                "m+": date.getMinutes(), //
                "s+": date.getSeconds(), //
                "q+": Math.floor((date.getMonth() + 3) / 3), //季度           
                "S": date.getMilliseconds() //毫秒           
            };
            var week = {
                "0": "/u65e5",
                "1": "/u4e00",
                "2": "/u4e8c",
                "3": "/u4e09",
                "4": "/u56db",
                "5": "/u4e94",
                "6": "/u516d"
            };
            if (/(y+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            if (/(E+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[date.getDay() + ""]);
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                }
            }
            return fmt;
        };
        /*
         * 倒计时
         * eg:
         * var obj=new TimeFormat();
         * obj.format(<msel>) ==> 08:09:04
         * ps:
         * <msel>为倒计时的毫秒数
         */
        this.countdown = function(msel,sign) {
            var hh, mm, ss;
            if (msel > 0) {
                msel = msel / 1000;
                hh = parseInt(msel / 3600);
                mm = parseInt((msel - hh * 3600) / 60);
                ss = parseInt(msel % 60);
            } else {
                hh = mm = ss = 0;
            }
            if (hh < 10) hh = "0" + hh;
            if (mm < 10) mm = "0" + mm;
            if (ss < 10) ss = "0" + ss;
            if(sign){
                return hh + sign + mm + sign + ss;
            }else{
                return hh + "小时" + mm + "分" + ss+ "秒";
            }
        }
        /*
         * 多久前
         * eg:
         * var obj=new TimeFormat();
         * obj.before(86400000) ==> 1天前
         * ps:
         * <msel>为倒计时的毫秒数
         */
        this.before = function(msel) {
            var minute = 1000 * 60,
                hour = minute * 60,
                day = hour * 24,
                halfamonth = day * 15,
                month = day * 30;
            var monthC = msel / month;
            var weekC = msel / (7 * day);
            var dayC = msel / day;
            var hourC = msel / hour;
            var minC = msel / minute;
            if (monthC >= 1) {
                result = parseInt(monthC) + "个月前";
            } else if (weekC >= 1) {
                result = parseInt(weekC) + "周前";
            } else if (dayC >= 1) {
                result = parseInt(dayC) + "天前";
            } else if (hourC >= 1) {
                result = parseInt(hourC) + "个小时前";
            } else if (minC >= 1) {
                result = parseInt(minC) + "分钟前";
            } else
                result = "刚刚";
            return result;
        }
    }
    module.exports = TimeFormat;
});

3、animate.js模块

  

/**
 * @name CSS3动态焦点图
 * @description 功能模块
 */
define(function(require, exports, module) {
    require('jquery');
    require('animate.css');//有关动画的css
    
    function ScrollBar(settings) {
        this.leftBtn       = settings.leftBtn || null;              //向左
        this.rightBtn      = settings.rightBtn || null;             //向右
        this.scrollBody    = settings.scrollBody;                   //轮播的整体区域
        this.holder        = settings.holder;                       //轮播的图片层
        this.indexBtn      = settings.indexBtn || null;             //快捷跳转按钮
        this.indexBtnClass = settings.indexBtnClass || null;        //快捷跳转按钮class
        this._autoPlay     = settings._autoPlay || false;           //是否自动播放
        this.scrollType    = settings.scrollType || "opacity";      //切换方式 默认为渐隐
        this._init().bindEvent();
    }
    ScrollBar.prototype = {
        _init: function() {
            var self = this;
            this.currentIndex = 0;                                                //当前轮播到第几张图
            this.targetIndex  = 0;                                                //当前轮播图要到第几张去
            this.itemNum      = this.holder.length;                               //一共几张图
            this.scrollSpeed  = 500;                                              //过渡动画速度
            if (this.css3Animate()){                                              //是否支持css3执行焦点图动画
                this.checkPicLoaded(this.holder.eq(this.currentIndex).show());
            }else{
                self.holder.each(function(index) {
                    var $self = $(this);
                    var bkgUrl = $self.attr("data-bkg");
                    if (bkgUrl) {
                        var _img = new Image();
                        _img.src = bkgUrl;
                        _img.index = index;
                        _img.onload = function() {
                            self.holder.eq(this.index).css("backgroundImage", "url(" + bkgUrl + ")");
                        }
                    }
                })
            }
            if (this._autoPlay) {                                                 //是否自动播放
            this.autoPlayLag  = 10000;                                            //自动播放间隔
            this.autoPlay();
            }
            return this;
        },
        bindEvent: function() {
            var self = this;
            this.leftBtn && this.leftBtn.bind("click", function() { //左翻
                self.targetIndex--;
                if (self.targetIndex < 0) self.targetIndex = self.itemNum - 1;
                self.scroll("left");
            })
            this.rightBtn && this.rightBtn.bind("click", function() { //右翻
                self.targetIndex++;
                if (self.targetIndex >= self.itemNum) self.targetIndex = 0;
                self.scroll("right");
            })

            this.indexBtn && this.indexBtn.bind("click", function() { //直接跳转
                if ($(this).index() > self.targetIndex) {
                    self.targetIndex = $(this).index();
                    self.scroll("right");
                } else if ($(this).index() < self.targetIndex) {
                    self.targetIndex = $(this).index();
                    self.scroll("left");
                }
            })

            this._autoPlay && this.scrollBody.bind("mouseenter", function() {
                clearInterval(self.timer);
                self.leftBtn.show();
                self.rightBtn.show();
            }).bind("mouseleave", function() {
                self.autoPlay();
                self.leftBtn.hide();
                self.rightBtn.hide();
            })
            return this;
        },
        scroll: function(type) {
            var self = this;
            this.indexBtn.removeClass(this.indexBtnClass).eq(this.targetIndex).addClass(this.indexBtnClass);
            var $current = this.holder.eq(this.currentIndex).show();
            if (this.css3Animate()) self.resetLayer($current);
            // console.log(this.targetIndex);
            var $target = this.holder.eq(this.targetIndex).show();
            if (this.title) {
                this.title.eq(this.currentIndex).hide();
                this.title.eq(this.targetIndex).show();
            }
            if (self.css3Animate()) self.checkPicLoaded($target)
            switch (this.scrollType) {
                case "opacity":
                    $target.css("opacity", 0)
                    $current.stop().animate({
                        opacity: 0
                    }, self.scrollSpeed, function() {
                        $current.hide();
                    })
                    $target.stop().animate({
                        opacity: 1
                    }, self.scrollSpeed)
                    break;
            }
            this.currentIndex = this.targetIndex;
        },
        autoPlay: function() {
            var self = this;
            if (this.timer) clearInterval(this.timer)
            this.timer = setInterval(function() {
                self.targetIndex++;
                if (self.targetIndex >= self.itemNum) self.targetIndex = 0;
                self.scroll("right");
            }, self.autoPlayLag);
        },
        checkPicLoaded: function(currentLayer) {
            var self = this;
            var $animateLayer = currentLayer.children("div");
            var length = $animateLayer.length;
            var loadedNum = 0;
            for (var i = 0; i < length; i++) {
                var _img = new Image();
                _img.src = $animateLayer.eq(i).attr("data-bkg");
                _img.onload = function() {
                    loadedNum++;
                    if (loadedNum == length) {
                        currentLayer.css("backgroundImage", "none");
                        self.animateLayer(currentLayer);
                    }
                }
            }
        },
        resetLayer: function(currentLayer) {
            var $animateLayer = currentLayer.children("div");
            $animateLayer.each(function() {
                $(this).removeClass($(this).attr("data-type"));
                if (!$(this).attr("data-isBg")) $(this).hide();
            })
        },
        animateLayer: function(currentLayer) {
            var self = this;
            var $animateLayer = currentLayer.children("div");
            var currentAnimateIndex = 0;
            var layerAry = [];
            var stepAry = [];
            $animateLayer.each(function() {
                layerAry.push($(this));
                $(this).removeClass($(this).attr("data-type"));
                var step = $(this).attr("data-delay");
                if (stepAry[step - 1]) {
                    stepAry[step - 1].push($(this));
                } else {
                    stepAry[step - 1] = [$(this)];
                }
            });
            clearInterval(this.animateTimer)
            this.animateTimer = setInterval(function() {
                if (stepAry[currentAnimateIndex]) {
                    for (var i = 0; i < stepAry[currentAnimateIndex].length; i++) {
                        var target = stepAry[currentAnimateIndex][i];
                        target.css("backgroundImage", "url(" + target.attr("data-bkg") + ")").show().addClass(target.attr("data-type"));
                    }
                }
                if (currentAnimateIndex > stepAry.length) {
                    clearTimeout(self.animateTimer)
                }
                currentAnimateIndex++;
            }, 100)
        },
        css3Animate:function(){
            var testDiv = document.createElement("div");
            var css3AnimateSupport = false;
            if ("oninput" in testDiv) {
                ["", "ms", "webkit"].forEach(function(prefix) {
                    var css3Animate = prefix + (prefix ? "A" : "a") + "nimation";
                    if (css3Animate in testDiv.style) {
                        css3AnimateSupport = true;
                    }
                });
            }
            return css3AnimateSupport;
        }
    };
    module.exports = ScrollBar;
});

感谢:钱庄网。

 

你可能感兴趣的:(seajs的一次尝试)