我试图找出一个问题,即在由 FlightJs 函数指定的事件被触发之前显示特定的 div。
define([
'flight',
'mixins/form'
], function(flight, formMixin) {
function forgotPasswordForm() {
this.attributes({
submitButtonSelector: '.btn-submit',
formSelector: '#forgot-password',
successMessageSelector: '.success-message',
successMessageEmailSelector: '.success-message span.success-email',
emailInputSelector: '#forgot-password #email',
errorSelector: '#forgot-password .error-message'
});
this.after('initialize', function() {
this.on('click', {
'submitButtonSelector': this.onSubmitButtonClicked
});
this.on('keyup keypress', {
'formSelector': this.onFormKeyUp
});
});
this.onFormKeyUp = function(event) {
// Capture and deal with "Enter" key being pressed.
var keyCode = event.keyCode || event.which;
if (keyCode == 13) {
event.preventDefault();
this.onSubmitButtonClicked();
return false;
}
};
this.onSubmitButtonClicked = function(event) {
var email = this.select('emailInputSelector').val();
if (email.length > 0) {
this.select('errorSelector').hide();
this.postForm(this.select('formSelector'))
// Show success message on error to hide malicious password resetting.
.error(this.showSuccessMessage(email))
.done(this.showSuccessMessage(email));
} else {
this.select('errorSelector').show();
}
};
this.showSuccessMessage = function(email) {
this.select('successMessageSelector').show();
this.select('successMessageEmailSelector').text(email);
};
}
flight.component(forgotPasswordForm, formMixin).attachTo('.forgot-password-form');
});
如您所见,在检测到初始化后,我为 onSubmitButtonClicked 指定了 on click 事件。
在 onSubmitButtonClicked 函数中,我收集字段值并将其传递给混合“表单”中指定的请求处理程序,如下所示:
define([], function() {
'use strict';
function formMixin() {
/*
* Use an existing form to post data asynchronously, in order to avoid
* hard coding URLs and data transformation on Javascript.
*/
this.postForm = function($form) {
return $.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize()
});
};
}
return formMixin;
});
问题是 showSuccessMessage()
函数在初始化后立即触发,而不是在等待 Submitbuttonclicked 后触发。 error 和 done 的回调链接是否不正确,或者代码是否存在其他问题?
最佳答案
假设您在某处有一个有效的 require.js/webpack 配置,您没有使用任何 CSS 类来隐藏消息元素,并且您的标记如下所示:
<div class="forgot-password-form">
<form id="forgot-password" method="GET"
action="https://jsonplaceholder.typicode.com/comments">
<input id="email">
<div class="error-message">
Error!
</div>
</form>
<button class="btn-submit">
Submit
</button>
<div class="success-message">
Success!
</div>
</div>
我想说您只是缺少隐藏 initialize
事件中的消息元素。
它应该看起来像这样:
// ...
this.after('initialize', function() {
this.on('click', {
'submitButtonSelector': this.onSubmitButtonClicked
});
this.on('keyup keypress', {
'formSelector': this.onFormKeyUp
});
this.select('successMessageSelector').hide();
this.select('errorSelector').hide();
});
// ...
我做了一个fiddle你可以去哪里看看。
关于javascript - 使用 FlightJS 的事件流不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44140249/