I need to populate all my app's collections before presenting any view. The problem is, however, sometimes I have to refresh the page a few times before I see that all have been populated.
As an example, sometimes the rooms collection is completely empty when I know that there are rooms in the database. In this case, the server response is empty.
Here is a stripped down implementation:
(function() {
window.rooms = new App.Collections.Rooms();
$.when(rooms.fetch()).done(function() {
window.router = new App.Router;
Backbone.history.start();
});
}());
This is the code that returns rooms from the server:
public function get_index() {
$rooms = Room::where('id_hostel', '=', Session::get('id_hostel'))->get();
$response = array();
foreach($rooms as $room) {
$response[] = $room->attributes;
}
return json_encode($response);
}
Actually I don't know if the error is on the client side or in the Laravel RESTful service I've programmed. How can I fix this intermittent problem?
There are few ways to handle this if you refer - Collection fetch
First way is already mentioned by Sidney and that's using fetch
and success
callback.
Second way is using events
, which, in my opinion is better because you can decouple code easier with better readability.
var rooms = window.rooms = new App.Collections.Rooms();
rooms.fetch();
...
rooms.on('sync', someFunction);
or
var rooms = window.rooms = new App.Collections.Rooms();
rooms.fetch({reset: true});
...
rooms.on('reset', someFunction);
someFunction () {
window.router = new App.Router;
Backbone.history.start();
}
Tho I must say this is not the preferred "Backbone way" of doing things. I strongly encourage you to read Backbone Patterns
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.