javascript - jquery订阅函数返回错误
问题描述
具有由多个元素的更改事件调用的以下函数。
function multipleTests(){
if(Test_X == false){
return false;
}
if(Test_Y == false){
return false;
}
// all tests passed release save button
releaseButton();
}
我想下标“返回错误事件”。像这样的东西:
multipleTest.bind("return false", function(){
// do something here, like reset fields, other tests etc.
});
我必须更改函数multipleTests 吗?
我可以以某种方式使用try catch吗?
我可以以某种方式使用承诺对象吗?
解决方案
您可以做的是创建并触发自定义事件:
// create your custom event
var customEvent = new CustomEvent('my-custom-event',{
detail: {
tests: {
x: null,
y: null
}
}
});
// Listen for the event.
// You have to do this BEFORE dispatching the event
document.addEventListener('my-custom-event', function (e) {
// print out the event detail
console.log(JSON.stringify(e.detail));
}, false);
//triggered when the button is clicked
function multipleTests(){
var Test_X = true;
var Test_Y = false;
//assign the outcome of the tests to the event detail
customEvent.detail.tests.x = Test_X;
customEvent.detail.tests.y = Test_Y;
if(Test_X == false){
document.dispatchEvent(customEvent);
return false;
}
if(Test_Y == false){
document.dispatchEvent(customEvent);
return false;
}
// all tests passed release save button
// releaseButton();
}
<input type=button value="trigger event" onclick="multipleTests()"/>
参考:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events