Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing JSON data on trigger

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"}

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

like image 399
Anwar Chandra Avatar asked Dec 19 '25 08:12

Anwar Chandra


2 Answers

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"}]
});
like image 164
Crescent Fresh Avatar answered Dec 21 '25 22:12

Crescent Fresh


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

like image 36
jitter Avatar answered Dec 21 '25 23:12

jitter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!