Json data transfer at startup

I am calling a service that returns 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 an example response:

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

when obj received the SOME_EVENT trigger, I expect it to pass the message data below:

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

but when I printed the message options for the console,

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

he just relayed the last message below

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

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

+3
source share
2 answers

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

response.messages - , :

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

:

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"}]
});
+6

crescentfresh , .

. trigger,

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

console.log(messages); ,

+3

Source: https://habr.com/ru/post/1721331/


All Articles