gpt4 book ai didi

javascript - AngularJS退出递归函数调用

转载 作者:行者123 更新时间:2023-12-02 15:54:35 25 4
gpt4 key购买 nike

我使用以下函数从 REST API 获取用户,按偏移量分页。 在成功回调上,该函数会使用新的偏移量再次递归调用,以获取下一个垃圾用户。

问题:如果我切换或离开 View ,FetchAttendee-Function 将运行,直到获取所有用户。但是,为了提高性能,我想停止为用户获取数据。

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

那么,是否可以停止在查看离开事件上调用fetchAttendee-Function

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

最佳答案

这是伪代码(未经测试您想要做什么)

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

如果 [DO SOMETHING WITH RESPONSE ] 包括将其绑定(bind)到 View 的范围,那么您必须添加代码以使服务通知 Controller 数据已更改。

在这种情况下,您可以使用 $rootScope、$on 和 $emit 在获取与会者时从服务发出一条消息,以便 Controller 可以监听并更新。这是一个简单的例子:

// in the controller
$rootScope.$on("AttendeeFetchedEvent", function($event, data){
// do something with data
});

// in the factory/service
$scope.$emit("AttendeeFetchedEvent", dataToSendToController);

关于javascript - AngularJS退出递归函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31659057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com