I use the following function the fetch users from a REST API, paginated by offset. On Success-Callback
, the function gets called again recursively with a new offset to fetch the next junk of users.
Problem: If I switch or leave the view, the FetchAttendee-Function
runs until all users are fetched. However to increase performance, I would like to stop fetching for users.
fetchAttendees(event_id, offset);
function fetchAttendees(event_id, offset) {
AttendeeFactory(offset).show({id: event_id},
function success(response) {
[ DO SOMETHING WITH RESPONSE ]
fetchAttendees(event_id, offset);
},
function (error) {
});
}
So, is it possible to stop calling the fetchAttendee-Function on the view leave Event?
$scope.$on("$ionicView.leave", function(scopes, states) {
[ ...]
});
AttendeeFactory
.factory('AttendeeFactory', function ($resource) {
return function (offset) {
return $resource('http://10.0.0.6:8000/backend/attendees/:id/', {}, {
show: { method: 'GET', headers: {'attendee-offset': offset}, isArray: true }
});
};
})
Here is the pseudo-code (untested for what you want to do)
// in your controller
app.controller('YourController', ['$scope', 'AttendeeFactory', function($scope, AttendeeFactory) {
...
AttendeeFactory.fetchAttendees(event_id, offset);
...
}]);
// in the state change handler that matches leaving your view
AttendeeFactory.pause();
// in your service/factory
app.factory('AttendeeFactory', function($resource) {
var isPaused = true;
function fetchAttendees(event_id, offset) {
isPaused = false;
fetchAttendeesRecursive(event_id, offset);
}
function fetchAttendeesRecursive(event_id, offset) {
if (!isPaused) {
Attendee(offset).show(
{id: event_id},
function success(response) {
[ DO SOMETHING WITH RESPONSE ]
fetchAttendees(event_id, offset);
},
function (error) {}
);
}
}
function Attendee(offset) {
return = $resource(
'http://10.0.0.6:8000/backend/attendees/:id/',
{},
{
show: {
method: 'GET',
headers: {'attendee-offset': offset},
isArray: true
}
}
);
}
function pause() { isPaused = true; }
return {
fetchAttendees: fetchAttendees,
pause: pause
};
});
if the [ DO SOMETHING WITH RESPONSE ] includes binding it to the view's scope, then you have to add code to have the service notify the controller that the data has changed.
In that case you can use $rootScope, $on and $emit to emit a message from the service when an attendee is fetched so that the controller can listen to it and update. Here is a simple example:
// in the controller
$rootScope.$on("AttendeeFetchedEvent", function($event, data){
// do something with data
});
// in the factory/service
$scope.$emit("AttendeeFetchedEvent", dataToSendToController);