3

我在结合 jQuery JSON 调用的情况下使用 Javascript 变量范围。不幸的是,我不能在 jsFiddle 上发布这个脚本,因为它需要一些数据。

我正在尝试动态加载数据并将其输出到用户的屏幕上。我现在只创建了第一次加载数据的方法。稍后我想创建一个更新方法来更新表行中的数据。

但是现在我遇到了变量范围的问题。调用 $.pcw.outstandingInvoices.init() 时,出现以下错误:

ypeError: can't convert undefined to object
this.outstandingInvoicesArray[key] = entry;

我的代码:

-- Post is getting to long, so removed the first code i've used. -- 

谁能告诉我我做错了什么,以便我可以修复它?

提前致谢!

--- 更新 --- 我已经编辑了你们告诉我的东西,但我仍然遇到错误......谁能告诉我我做错了什么?

我的新代码和错误:

-- Post is getting to long, so removed the first update of the code. -- 

错误:

Initializing outstandingInvoices class.
Loading outstanding invoices from server.

TypeError: context.outstandingInvoicesObject is undefined
if (context.outstandingInvoicesObject.length == 0) {

TypeError: can't convert undefined to object
self.outstandingInvoicesObject[key] = entry;

-- 更新 2 -- 刚刚编辑了我的代码,现在我没有收到错误,但未正确保存未正确保存的数据,因此方法 addOutstandingInvoicesTable 找不到任何发票。我一直在分析控制台,似乎方法的执行顺序有问题......

编码:

$.pcw.outstandingInvoices = function () {
    var context = this;
    context.outstandingInvoicesObject = [];

    context.init = function ()
    {
        console.log('Initializing outstandingInvoices class.');

        context.loadData();        
        context.removeLoader();
        context.addOutstandingInvoicesToTable();
    };

    context.loadData = function ()
    {
        console.log('Loading outstanding invoices from server.');

        jQuery.getJSON('/ajax/outgoing-invoices/find-outstanding.json', function (data)
        {   
            var i = 0;
            jQuery.each(data, function (key, entry)
            {
                context.outstandingInvoicesObject[key] = entry;

                ++i;
            });

            console.log('Loaded ' + i + ' invoices');
        }).error(function () {
            console.error('Error while loading outstanding invoices.');
        });
    };

    context.removeLoader = function ()
    {
        console.log('Removing loader');

        jQuery('table#invoices-outstanding tr.ajax-loader').fadeOut();
    };

    context.addOutstandingInvoicesToTable = function()
    {
        console.log('Outputing invoices to table');

        if (context.outstandingInvoicesObject.length == 0) {
            console.log('No outstanding invoices found');
        }

        jQuery.each(context.outstandingInvoicesObject, function (key, entry)
        {
            // This is a new outstanding invoice
            var rowClass = 'info';

            switch(entry.status)
            {
                case 'Created':
                case 'Sent':
                case 'Paid': // The invoices with Paid statuses aren't show here, because we only show the oustanding invoices on this page.
                    rowClass = 'success';
                break;

                case 'First reminder':
                case 'Second reminder':
                case 'Partially paid':
                    rowClass = 'warning';
                break;

                case 'Third reminder':
                case 'Collection agency':
                case 'Judicial proceedings':
                    rowClass = 'error';
                break;
            }

            jQuery('table#invoices-outstanding tbody').append(
                outstandingInvoice = jQuery('<tr/>', {
                    id: 'outgoing-invoice-' + key,
                    class: rowClass
                }).append(
                    jQuery('<td/>', {
                        class: 'id',
                        text: key
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'debtor-name',
                        text: entry.debtor_name
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'amount',
                        text: entry.amount
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'date',
                        text: entry.created_timestamp
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'status',
                        text: entry.status
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'creator',
                        text: entry.creator
                    })
                )            
            );
        });
    }
}


// When document is ready
(function()
{
    var invoices = new $.pcw.outstandingInvoices();
    invoices.init();
})();

控制台输出:

Initializing outstandingInvoices class.

Loading outstanding invoices from server.
GET /ajax/outgoing-invoices/find-outstanding.json
200 OK
509ms   

Removing loader

Outputing invoices to table

No outstanding invoices found

Loaded 29 invoices

谢谢

4

5 回答 5

1

以下应该可以解决您的问题。您没有按照您的意图声明 oustandingInvoicesObject 。在您的情况下,它必须关闭“this”或“context”。

此外,您将 oustandingInvoicesObject 声明为 Array 而不是 Object。您不能像添加对象那样向数组添加属性。

让我知道事情的后续。

$.pcw.outstandingInvoices = function () {
    var context = this;
    context.outstandingInvoicesObject = {};

    context.init = function ()
    {
        console.log('Initializing outstandingInvoices class.');

        context.loadData();
        context.removeLoader();
        context.addOutstandingInvoicesToTable();
    };

    context.loadData = function ()
    {
        console.log('Loading outstanding invoices from server.');

        var self = this;

        jQuery.getJSON('/ajax/outgoing-invoices/find-outstanding.json', function (data)
        {            
            jQuery.each(data, function (key, entry)
            {
                self.outstandingInvoicesObject[key] = entry;
            });
        }).error(function () {
            console.error('Error while loading outstanding invoices.');
        });
    };

    context.removeLoader = function ()
    {
        jQuery('table#invoices-outstanding tr.ajax-loader').fadeOut();
    };

    context.addOutstandingInvoicesToTable = function()
    {
        if (context.outstandingInvoicesObject.length == 0) {
            console.log('No outstanding invoices found');
        }

        jQuery.each(context.outstandingInvoicesObject, function (key, entry)
        {
            // This is a new outstanding invoice
            var rowClass = 'info';

            switch(entry.status)
            {
                case 'Created':
                case 'Sent':
                case 'Paid': // The invoices with Paid statuses aren't show here, because we only show the oustanding invoices on this page.
                    rowClass = 'success';
                break;

                case 'First reminder':
                case 'Second reminder':
                case 'Partially paid':
                    rowClass = 'warning';
                break;

                case 'Third reminder':
                case 'Collection agency':
                case 'Judicial proceedings':
                    rowClass = 'error';
                break;
            }

            jQuery('table#invoices-outstanding tbody').append(
                outstandingInvoice = jQuery('<tr/>', {
                    id: 'outgoing-invoice-' + key,
                    class: rowClass
                }).append(
                    jQuery('<td/>', {
                        class: 'id',
                        text: key
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'debtor-name',
                        text: entry.debtor_name
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'amount',
                        text: entry.amount
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'date',
                        text: entry.created_timestamp
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'status',
                        text: entry.status
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'creator',
                        text: entry.creator
                    })
                )            
            );
        });
    };
};

// When document is ready
(function(){
    var invoices = new $.pcw.outstandingInvoices();
    invoices.init();
})();
于 2013-02-01T19:42:02.623 回答
1

您正在创建outstandingInvoicesArray一个数组,但您试图将它作为一个对象访问:

outstandingInvoicesArray: []
[...]
this.outstandingInvoicesArray[key] = entry;

而是将其创建为对象:

outstandingInvoicesArray: {}
于 2013-01-31T20:44:27.977 回答
1

如果要使用this ,则应在初始化对象时使用new关键字:

$.pcw.outstandingInvoices = function(){
   var context = this;//replace every instance of "this" in your class with the context var

   context.init= function ()
    {
        console.log('Initializing outstandingInvoices class.');

        context.loadData();

    }
    //the rest of functions defined below
}
var invoices = new $.pcw.outstandingInvoices();
invoices.init();

编辑:要修复剩余的错误,请尝试使用上下文而不是 self,并在上下文中声明出色的 InvoicesObject:

$.pcw.outstandingInvoices = function () {
    var context = this;
    context.outstandingInvoicesObject = [];

    context.init = function ()
    {
        console.log('Initializing outstandingInvoices class.');

        context.loadData();

    };

    context.loadData = function ()
    {
        console.log('Loading outstanding invoices from server.');



        jQuery.getJSON('/ajax/outgoing-invoices/find-outstanding.json', function (data)
        {            
            jQuery.each(data, function (key, entry)
            {
                context.outstandingInvoicesObject[key] = entry;
            });
            //now that we have data, call add the invoices to the table
            context.removeLoader();
            context.addOutstandingInvoicesToTable();
        }).error(function () {
            console.error('Error while loading outstanding invoices.');
        });
    };

    context.removeLoader = function ()
    {
        jQuery('table#invoices-outstanding tr.ajax-loader').fadeOut();
    };

    context.addOutstandingInvoicesToTable = function()
    {
        if (context.outstandingInvoicesObject.length == 0) {
            console.log('No outstanding invoices found');
        }

        jQuery.each(context.outstandingInvoicesObject, function (key, entry)
        {
            // This is a new outstanding invoice
            var rowClass = 'info';

            switch(entry.status)
            {
                case 'Created':
                case 'Sent':
                case 'Paid': // The invoices with Paid statuses aren't show here, because we only show the oustanding invoices on this page.
                    rowClass = 'success';
                break;

                case 'First reminder':
                case 'Second reminder':
                case 'Partially paid':
                    rowClass = 'warning';
                break;

                case 'Third reminder':
                case 'Collection agency':
                case 'Judicial proceedings':
                    rowClass = 'error';
                break;
            }

            jQuery('table#invoices-outstanding tbody').append(
                outstandingInvoice = jQuery('<tr/>', {
                    id: 'outgoing-invoice-' + key,
                    class: rowClass
                }).append(
                    jQuery('<td/>', {
                        class: 'id',
                        text: key
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'debtor-name',
                        text: entry.debtor_name
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'amount',
                        text: entry.amount
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'date',
                        text: entry.created_timestamp
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'status',
                        text: entry.status
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'creator',
                        text: entry.creator
                    })
                )            
            );
        });
    }
}
于 2013-01-31T20:44:49.393 回答
1

创建对象的备份,以便您可以在this不引用该对象的函数中使用它。

loadData: function ()
{
    console.log('Loading outstanding invoices from server.');
    var self = this;
    jQuery.getJSON('/ajax/outgoing-invoices/find-outstanding.json', function (data)
    {            
        jQuery.each(data, function (key, entry)
        {
            self.outstandingInvoicesArray[key] = entry;
        });
    }).error(function () {
        console.error('Error while loading outstanding invoices.');
    });
},
于 2013-01-31T20:42:32.597 回答
0

现在问题已经解决了。这是你们所说的事情和AJAX调用是异步的问题的结合。

最终的工作代码是:

$.pcw.outstandingInvoices = function () {
    var context = this;
    context.outstandingInvoicesObject = new Object();

    context.init = function ()
    {
        console.log('Initializing outstandingInvoices class.');

        context.loadData();                
        context.removeLoader();
        context.addOutstandingInvoicesToTable();
    };

    context.loadData = function ()
    {
        console.log('Loading outstanding invoices from server.');

        $.ajax({
            url: '/ajax/outgoing-invoices/find-outstanding.json',
            dataType: 'json',
            async: false,
            success: function(data) {                
                var i = 0;            
                jQuery.each(data, function (invoiceId, invoiceDetails)
                {
                    context.outstandingInvoicesObject[invoiceId] = invoiceDetails;

                    ++i;                                
                });

                console.log('Loaded ' + i + ' invoices');       
            }
        }).error(function () {
            console.error('Error while loading outstanding invoices.');
        });
    };

    context.removeLoader = function ()
    {
        console.log('Removing loader');

        jQuery('table#invoices-outstanding tr.ajax-loader').fadeOut();
    };

    context.addOutstandingInvoicesToTable = function()
    {
        console.log('Outputing invoices to table');           

        if (context.outstandingInvoicesObject.length == 0) {
            console.log('No outstanding invoices found');            
        }

        jQuery.each(context.outstandingInvoicesObject, function (key, entry)
        {
            // This is a new outstanding invoice
            var rowClass = 'info';

            switch(entry.status)
            {
                case 'Created':
                case 'Sent':
                case 'Paid': // The invoices with Paid statuses aren't show here, because we only show the oustanding invoices on this page.
                    rowClass = 'success';
                break;

                case 'First reminder':
                case 'Second reminder':
                case 'Partially paid':
                    rowClass = 'warning';
                break;

                case 'Third reminder':
                case 'Collection agency':
                case 'Judicial proceedings':
                    rowClass = 'error';
                break;
            }

            jQuery('table#invoices-outstanding tbody').append(
                outstandingInvoice = jQuery('<tr/>', {
                    id: 'outgoing-invoice-' + key,
                    class: rowClass
                }).append(
                    jQuery('<td/>', {
                        class: 'id',
                        text: key
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'debtor-name',
                        text: entry.debtor_name
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'amount',
                        text: entry.amount
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'date',
                        text: entry.created_timestamp
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'status',
                        text: entry.status
                    })
                ).append(
                    jQuery('<td/>', {
                        class: 'creator',
                        text: entry.creator
                    })
                )            
            );
        });
    }
}

// When document is ready
(function()
{   
    var invoices = new $.pcw.outstandingInvoices();
    invoices.init();
})();

谢谢你们的帮助,伙计们!

于 2013-02-02T11:23:43.453 回答