在return语句中访问JS函数

时间:2014-01-01 18:27:43

标签: javascript requirejs

如何从以下代码中的showDashboard访问功能showTimeline$(...)

define(["jquery", "bootstrap", "./timeline"], function($, bootstrap, timeline) {

$(function(){

    $("#right-menu-dashboard").click(function(){
        // I would like to access the showDashboard function here...
        showDashboard();
    });

    $("#right-menu-timeline").click(function(){
        // ... and the showTimeline function here.
        showTimeline();
    });

    return {

        showDashboard: function() {
            // Some code here
        },

        showTimeline: function() {
            // And here too!
        }
    }
});

2 个答案:

答案 0 :(得分:3)

有两种方法。我可能会这样做:

define(["jquery", "bootstrap", "./timeline"], function($, bootstrap, timeline) {

$(function(){

    $("#right-menu-dashboard").click(function(){
        // I would like to access the showDashboard function here...
        showDashboard();
    });

    $("#right-menu-timeline").click(function(){
        // ... and the showTimeline function here.
        showTimeline();
    });

    function showDashBoard() {
        // Some code here
    }

    function showTimeline() {
        // And here too!
    }

    return {
        showDashboard: showDashboard,
        showTimeline:  showTimeline
    };
});

但是这里的 minimal mod将会这样做:

define(["jquery", "bootstrap", "./timeline"], function($, bootstrap, timeline) {

$(function(){
    var obj;

    $("#right-menu-dashboard").click(function(){
        // I would like to access the showDashboard function here...
        obj.showDashboard();
    });

    $("#right-menu-timeline").click(function(){
        // ... and the showTimeline function here.
        obj.showTimeline();
    });

    obj = {

        showDashboard: function() {
            // Some code here
        },

        showTimeline: function() {
            // And here too!
        }
    };
    return obj;
});

或者这可能更清洁一点(只需更少的mod):

define(["jquery", "bootstrap", "./timeline"], function($, bootstrap, timeline) {

$(function(){
    var obj = {

        showDashboard: function() {
            // Some code here
        },

        showTimeline: function() {
            // And here too!
        }
    };

    $("#right-menu-dashboard").click(function(){
        // I would like to access the showDashboard function here...
        obj.showDashboard();
    });

    $("#right-menu-timeline").click(function(){
        // ... and the showTimeline function here.
        obj.showTimeline();
    });

    return obj;
});

但请注意,这些之间存在差异。当您调用showDashboard(例如)时,在第一个调用期间,this将是全局对象(处于松散模式)或undefined(处于严格模式下)。在后两个中,它将是您从$返回的对象。如果您未在这些功能中使用this,则无关紧要;如果你是,那就是。

答案 1 :(得分:2)

您需要先定义函数,然后使用它们,然后返回它们。

define(['foo'], function(foo) {
    function showDashboard() {...}

    $('#right-menu-dashboard').click(function() {
        showDashboard(); 
    });

    return {
        showDashboard: showDashboard
    };
});
相关问题