0

I am currently developing a single page app and i am using backbonejs for the same . My backend response is JSON , i am fetching using fetch() method . The problem i am facing the userNames attribute is populated with proper values only when i use fetch({async:false}),if i use fetch() i get an empty response .

Am i doing any something wrong? Am i missing something obvious ? My code is as below .

$(document).ready(function(){
    var booking_model = Backbone.Model.extend({});

    var UserList = Backbone.Collection.extend({ 
    model: booking_model,
    url: 'js/bookings.json',
    parse: function(response) {return response};


});





    var users = new UserList(); //Line 26
    users.fetch({async: false});
    var userNames = users.pluck("bookingId");
    console.log(userNames)
});

My JSON

[
        {
            "bookingId": 260,
            "bookingSourceId": "Online",
            "bookingTime": "Jan1391312: 00: 00AM",
            "noOfPeople": "10",
            "reserveDate": "ThuJan0200: 00: 00IST3913",
            "restId": 200,
            "timing_id": 200
        },
        {
            "bookingId": 280,
            "bookingTime": "Dec25 20121: 43: 49AM",
            "noOfPeople": "6",
            "reserveDate": "ThuJan2600: 00: 00IST2012",
            "restId": 220,
            "timing_id": 205
        },
        {
            "bookingId": 300,
            "bookingTime": "Dec26 20122: 12: 00AM",
            "noOfPeople": "4",
            "reserveDate": "FriJan2700: 00: 00IST2012",
            "restId": 260,
            "timing_id": 220
        },
        {
            "bookingId": 320,
            "bookingTime": "Dec27 20122: 14: 54AM",
            "noOfPeople": "10",
            "reserveDate": "SunJan2900: 00: 00IST2012",
            "restId": 260,
            "timing_id": 201
        },
        {
            "bookingId": 340,
            "bookingTime": "Dec25 20122: 35: 19AM",
            "noOfPeople": "8",
            "reserveDate": "TueJan2400: 00: 00IST2012",
            "restId": 220,
            "timing_id": 205
        },
        {
            "bookingId": 360,
            "bookingSourceId": "Online",
            "bookingTime": "May30 391312: 00: 00AM",
            "noOfPeople": "10",
            "reserveDate": "FriMay3000: 00: 00IST3913",
            "restId": 200,
            "timing_id": 200,
            "bookingUser": "hareesh",
            "bookingPhoneNo": "9052228181",
            "bookingEmail": "makamhareesh@gmail.com"
        }



    ]
4

1 回答 1

4

你错过了一些明显的东西:

users.fetch({
  success: function() {
    var userNames = users.pluck("bookingId");
    console.log(userNames)
  }
});

当“获取”操作是异步的时,紧随其后的代码将在 HTTP 操作完成之前运行很长时间。

于 2013-05-30T16:21:33.710 回答