如何通过requireJs从模块文件加载函数?

时间:2015-05-07 06:33:38

标签: javascript jquery requirejs

我是requireJS的新手。这是代码:

//main.js
require.config({
    baseUrl: "./js",
    paths: {
        "jquery"    : "jquery-2.1.1.min",
        "ui"        : "ui",
        "funcs"     : "funcs"
    }
});

require(["funcs"]);

//ui.js
define(["jquery", "funcs"], function($, f){
    return {
        setValue: function(selector, text){
            $(selector).text(text);
        },
        setBgColor: function(hexCode){
            $("body").css("background-color", hexCode);
        }
    };
});

//funcs.js
    define(["jquery", "ui"], function($, u){
    return {
        setTimer: function(hours){
            var mSec = hours*3600;
            var timer = setInterval(function(){
                if(mSec<=0){
                    u.setBackgroundColor("#ff0000");
                }else{
                    var updateH = this.addZero(Math.floor(mSec/3600));
                    var updateM = this.addZero(Math.floor((mSec-updateH*3600)/60));
                    var updateS = this.addZero(Math.floor(mSec-updateH*3600-updateM*60));
                    //u.setValue(".display-countdown", updateH+":"+updateM+":"+updateS);
                    console.log(updateH+":"+updateM+":"+updateS);
                    mSec--;
                }
            }, 1000);
        },
        addZero: function(value){
            var n = parseInt(value);
            if(n<=9){
                return "0"+n.toString();
            }else{
                return n.toString();
            }
        }   
    }
});

在html中,我加载需要这样:

<script data-main="js/main" src="js/require.js"></script>

main.js是入口。我想在页面加载时从funcs.js加载setTimer函数。我是在main.js中做到的:

require(["funcs"], function(f){
    f.setTimer(2);
});

但它返回&#34;无法读取属性&#39; setTimer&#39;未定义&#34;和&#34; addZero未定义&#34;。有谁可以帮助我?

1 个答案:

答案 0 :(得分:-1)

固定代码:

define(["jquery", "ui"], function($, u){
    return {
        setTimer: function(hours){
            var mSec = hours*3600;
            var timer = setInterval(function(){
                if(mSec<=0){
                    u.setBgColor("#ff0000");
                }else{
                    var updateH = addZero(Math.floor(mSec/3600));
                    var updateM = addZero(Math.floor((mSec-updateH*3600)/60));
                    var updateS = addZero(Math.floor(mSec-updateH*3600-updateM*60));
                    u.setValue(".display-countdown", updateH+":"+updateM+":"+updateS);
                    console.log(updateH+":"+updateM+":"+updateS);
                    mSec--;
                }
            }, 1000);
        }
    };

    function addZero(value){
        var n = parseInt(value);
        if(n<=9){
            return "0"+n.toString();
        }else{
            return n.toString();
        }
    }   
});