views:

56

answers:

2

I am calling a service that return json data.

script:

$.ajax({
    type: "POST",
    url: "/some/service",
    dataType: "json",
    success: function(response) {
        if (response.status == "ok" && response.messages.length > 0) {

            // obj is a jQuery object
            obj.trigger(SOME_EVENT, response.messages);

        }
    }
});

this is the response example:

{
  "status":"ok",
  "messages":[
     {"id":1,"message_text":"latihan"},
     {"id":123,"message_text":"hello"}]
}

when obj received the SOME_EVENT trigger, I am expecting it to pass messages data below:

[{"id":1,"message_text":"latihan"},
 {"id":123,"message_text":"hello"}]

but when I printed messages parameter to console,

// on receiving messages
obj.bind(SOME_EVENT, function(sender, messages) {
    console.log(messages);
});

turn out, it only passed the last message below

{"id":123,"message_text":"hello"}

anyone can explain why the array of messages is not passed by my custom event?

+3  A: 

From http://docs.jquery.com/Events/trigger, the second parameter to the trigger function is an array of additional arguments (passed after the event object).

The value of your response.messages property is an array, so they are actually passed along to your handler as separate arguments:

obj.bind(SOME_EVENT, function(sender, message1, message2/*, etc*/) {
    console.log(message1); // {"id":1,"message_text":"latihan"}
    console.log(message2); // {"id":123,"message_text":"hello"}
});

You can collect them cleanly as one array with:

obj.bind(SOME_EVENT, function(sender) {
    var messages = Array.prototype.slice.call(arguments, 1);
    console.log(messages); // [{"id":1,"message_text":"latihan"},
                           //  {"id":123,"message_text":"hello"}]
});
Crescent Fresh
+1  A: 

crescentfresh answer is correct and both solutions work and are valid.

Here is a third option for you. You can call the trigger-method like this

obj.trigger(SOME_EVENT, new Array(response.messages));

then console.log(messages); will output what you expect

jitter
The shorter array notation will work as well `obj.trigger(SOME_EVENT, [response.messages]);`
joshperry
Actually, `console.log(messages[0])` would be needed to output what the OP expects.
Crescent Fresh