开发者

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

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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜