Javascript类变量范围

时间:2013-01-31 20:39:28

标签: javascript jquery json oop scope

我正在努力将Javascript变量范围与jQuery JSON调用结合起来。 不可思议的是,我不能在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 - 刚刚编辑了我的代码,现在我没有收到错误,但却没有正确保存outstandingInvoicesObject中的数据,因此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

由于

5 个答案:

答案 0 :(得分: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.');
    });
},

答案 1 :(得分:1)

您正在创建outstandingInvoicesArray数组,但您尝试将其作为对象进行访问:

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

将其创建为对象:

outstandingInvoicesArray: {}

答案 2 :(得分: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();

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

$.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
                    })
                )            
            );
        });
    }
}

答案 3 :(得分: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();
})();

答案 4 :(得分: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();
})();

感谢您的帮助,伙计们!