다음 json이 API 호출에서 반환되었습니다. 특정 유형의 이벤트가 특정 제품에 대해 로깅되었는지 확인하고 해당 메시지가 올바른 메시지를 반환하고 클릭 핸들러를 종료하는 경우 그렇지 않으면 계속 진행합니다. 이 검사를 수행하려면 hasEvent
이라는 기능이 있습니다. 그러나이 함수를 someOtherFunction
에서 호출 할 때 검사가 true 일 때도 메시지가 반환되지 않습니까?jQuery - 콜백이 작동하지 않습니다.
{
"item": {
"Event": [
{
"EventType": {
"Description": "New order"
},
"EventSubType": {
"Description": "Awaiting payment"
}
},
{
"EventType": {
"Description": "New order"
},
"EventSubType": {
"Description": "Dispatched"
}
}
],
"Errors": {
"Result": 0,
"Message": ""
},
"RecordCount": 2
}
}
var getEvents = function (callback) {
var orderId = $("#Id").val();
$.getJSON('api/events?id=' + orderId)
.done(function (data) {
callback(data);
}).fail(function (jqXHR, textStatus, err) {
return;
});
}
var hasEvent = function (productType, callback) {
var msg;
getEvents(function (data) {
_.find(data.item.Event, function (event) {
if (event.EventType.Description == 'New order' &&
event.EventSubType.Description == 'Dispatched' &&
productType = 'xyz') {
msg = 'Some message';
return true;
}
if (event.EventType.Description == 'New order' &&
event.EventSubType.Description == 'Awaiting payment' &&
productType = 'xyz') {
msg = 'A different message';
return true;
}
// Check for Some more conditions and return appropriate message
return false;
});
if (msg)
callback(msg);
});
}
var someOtherFunction = function() {
$('.myselector').click(function (e) {
var productType = $(this).attr("data-product-type");
hasEvent(productType, function(msg) {
alert(msg);
// exit click event handler
return;
});
// otherwise do some other stuff
return false;
}
}
위의 코드에 어떤 문제가 있습니까?
* UPDATE * 내가 경고가 표시 얻을 경우, 나는 다음 클릭 핸들러를 종료 어떻게 지금 hasEvent
함수에 콜백을 추가하지만 의해 그리핀 솔루션에 따라 코드를 업데이트 한
.
이$('.myselector').click(function (e) {
var productType = $(this).attr("data-product-type");
hasEvent(productType, function(eventMsg) {
alert(msg);
// exit click event handler
return;
});
// Do some other stuff only if no events
return false;
}
'// 클릭 이벤트 핸들러 종료 '가 잘못되었습니다. 또한'//이벤트가없는 경우에만 다른 것들을해라 .'도 콜백에 있어야한다. gogoasynchronouslogic –