我有以下json從api調用返回。我想檢查某些特定產品是否記錄了特定類型的事件,並且如果它真實地返回了適當的消息並退出點擊處理程序,否則繼續。我有一個名爲hasEvent
的功能來執行此檢查。但是當我從someOtherFunction
調用此函數時,即使檢查爲真,也不會返回任何消息嗎?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
功能,但是現在我如何退出以下click處理程序,如果獲得顯示提醒更新的代碼。
$('.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 –