模块化脚本中的未定义变量

时间:2015-07-27 23:24:27

标签: javascript arguments underscore.js modularity

我一直在努力使这个脚本更加模块化,我遇到了一个错误。我错误地命令我的逻辑吗?

错误消息

  

未捕获的ReferenceError:未定义accountId

相关脚本行

            _.each(_.omit(accounts, _.keys(result.data.accounts)), function (account) {
                accounts[accountId].push([result.timestamp.valueOf(), 0]);
            });

脚本

var debug = 0;

function paramsStr(p) {
    var first = true;
    var s = '';
    _.each(p,function (value,key) {
        if (!value) {
            return;
        }
        if (first) {
            s += '?';
            first = false;
        } else {
            s += '&';
        }
        s += key+'='+value;
    });
    return s;
};

function parseReport(data)
{
    var split = data.split('\n');
    var results = [];
    _.each(split,function (row) {
        if (!row || row == "") {
            return;
        }
        var myRow = JSON.parse(row);
        myRow.timestamp = moment.utc(myRow.timestamp);
        results.push(myRow);
    });

    return results;
}

function loadReport(report,granularity,startTime,endTime) {
    if (debug && _.has(mock.reports,report) && _.has(mock.reports[report],granularity)) {
        return jQuery.Deferred().resolve(parseReport(mock.reports[report][granularity])).promise();
    }

    var params = {
        granularity : granularity
    };

    if (startTime) {
        params['start-time'] = startTime.toISOString();
    }

    if (endTime) {
        params['end-time'] = endTime.toISOString();
    }

    var url = '//analytics.locuslabs.com/api/reports/'+report+paramsStr(params);

    return $.ajax({
        url : url,
        dataType : 'text'
    }).then(function (data) {
        return parseReport(data);
    });
};

$(document).ready(function () {
    var placeholder = $(".graph");
    var oneMonth = moment().utc().subtract(1, 'months');
    var twoWeeks = moment().utc().subtract(2, 'weeks');

    //Function call to get the current time
    function dateNow(target,timeFormat){
        $(placeholder).siblings(target).text(moment(Date.now()).format(timeFormat));
    }

    function pollData(apiRoot,increment,startDate,label){
        loadReport(apiRoot,increment, startDate).then(function (results) {
            var totals = [];
            var accounts = {};
            _.each(results, function (result) {
                totals.push([
                    result.timestamp.valueOf(),
                    result.data.total
                ]);

                _.each(result.data.accounts, function (account, accountId) {
                    if (!_.has(accounts, accountId)) {
                        accounts[accountId] = {
                            label: account.account.name,
                            data: []
                        };
                    }
                    accounts[accountId].data.push([
                        result.timestamp.valueOf(),
                        account.total
                    ]);
                });

                _.each(_.omit(accounts, _.keys(result.data.accounts)), function (account) {
                    accounts[accountId].push([result.timestamp.valueOf(), 0]);
                });
            });
            var data = [{
                data: totals,
                label: label
            }];
            _.each(accounts, function (account) {
                data.push(account);
            });
            $(this > ".graph").plot(data, {
                grid: {
                    hoverable: true
                },
                tooltip: {
                    show: true
                },
                xaxis: {
                    mode: "time"
                },
                yaxis: {
                    axisLabel: label
                },
                legend: {
                    container: $(this > ".legend")
                },
                selection: {
                    mode: "x"
                }
            });
        });
        // Reload function within pollData function
        document.getElementById(apiRoot + "-reload").addEventListener("click", function() {
            pollData(apiRoot,increment,startDate,label);
            dateNow(".status","M/D/YYYY H:mm Z");
        }, false);
    }

    //Load Reports
    pollData('total-installs', 'day', oneMonth, "Total Installs");
    pollData('installs', 'hour', twoWeeks, "Installs (by hour)");
    pollData('sessions', 'day', twoWeeks, "Sessions");
    pollData('sessions-length', 'day', twoWeeks, "Session Length");

    // Selection Feature
    // TODO: Add Zoom to selection
    // TODO: Overview of Available Data when zoomed.

    placeholder.bind("plotselected", function (event, ranges) {

        var begin = ranges.xaxis.from.valueOf();
        var end = ranges.xaxis.to.valueOf();

        $(this).siblings(".selection").text(moment(begin).format("M/D/YYYY H:mm Z") + " to " + moment(end).format("M/D/YYYY H:mm Z"));

        /*
        var zoom = $("#zoom").prop("checked");

        if (zoom) {
            $.each(plot.getXAxes(), function(_, axis) {
                var opts = axis.options;
                opts.min = ranges.xaxis.from;
                opts.max = ranges.xaxis.to;
            });
            plot.setupGrid();
            plot.draw();
            plot.clearSelection();
        }
        */
    });

    // Update on Initial Poll
    // TODO: Ask for location and provide local time.
    dateNow(".status","M/D/YYYY H:mm Z");
});

1 个答案:

答案 0 :(得分:0)

您的函数

中没有accountId参数

<form action="/postPhotos" enctype="multipart/form-data" method="post"> <input type="file" name="photo"> <input type="submit" value="Upload photo"> </form>