adrianmcli
adrianmcli

Reputation: 1996

Javascript: pushing an object into a collection

I have a Msg object and a MsgCollection object.

Msg object:

function Msg(text, timestamp, source, thread_id) {
    Msg.RECEIVED = 1;
    Msg.SENT = 2;

    this.thread_id = thread_id;
    this.text = text;
    this.timestamp = timestamp;
    this.source = source;
}

MsgCollection object:

function MsgCollection() {
    this.all = [];
}
MsgCollection.prototype.push = function(msg) {
    this.all.push(msg);
    console.log("first message text: " + this.all[0].text);
}

In the following code, I take the result object and put all the data into a temporary Msg object before pushing it to a MsgCollection:

var msgColl = new MsgCollection();
for (var i = 0; i < result.texts.length; i++) {
    var tempMsg = new Msg;
    tempMsg.thread_id = result.texts[i].thread_id;
    tempMsg.text = result.texts[i].message;
    tempMsg.timestamp =  Number(result.texts[i].time_received);
    tempMsg.source = result.texts[i].type;

    msgColl.push(tempMsg);
}

Unfortunately, it seems that execution is stopped when I try to print out this.all[0].text in the push method. In other words, nothing seems to be getting pushed into the msgCollection object. Maybe this is a bit complex, but maybe I can receive some guidance on how to debug?

Thanks

Upvotes: 1

Views: 76

Answers (2)

Amol M Kulkarni
Amol M Kulkarni

Reputation: 21639

Try the following code:

for (var i = 0; i < result.texts.length; i++) {
    var tempMsg = new Msg();
    tempMsg.thread_id = result.texts[i].thread_id;
    tempMsg.text = result.texts[i].message;
    tempMsg.timestamp = new Number(result.texts[i].time_received);
    tempMsg.source = result.texts[i].type;

    msgColl.push(tempMsg);
}

And as you asked for 'guidance on how to debug' you can always choose chrome developer's tools else I recommend to go with firebug

Else for simpler debugging you can do the following as well(You can use a try-catch):

try {
   //Your code goes here..
   alert(Obj); //You can Inspect an object here..
}
catch(e) {
    //If any error you will inspect here..
    alert(e); 
}

I think this can help you..

Upvotes: 0

Ilya
Ilya

Reputation: 29703

var tempMsg = new Msg(); 

and

tempMsg.timestamp = new Number(result.texts[i].time_received);  

works well
DEMO

Upvotes: 3

Related Questions