gpt4 book ai didi

javascript - 如何选择性地忽略 knockout 'submit' 绑定(bind)?

转载 作者:行者123 更新时间:2023-12-03 11:12:36 25 4
gpt4 key购买 nike

我有一个带有 knockout 绑定(bind)的表单data-bind="submit: saveProfileChanges"。 viewmodel 函数 saveProfileChanges 调用以下新代码:

dataAccess.submitJsonWithFileRequestjQueryWithErrorFunction = function () {
function uploadImageComplete() {
// Hanlde response from image post.
}
$("#upload_iframe").load(function() {
uploadImageComplete();
});
$("#userProfileForm").submit();
};

我添加了此代码,以允许使用 iframe 后备为 IE9 上传伪 ajax 图像。我已经尝试使用 jquery 插件进行上传,但没有成功,并决定采用一种简单明了的方法风险较小,并最大限度地减少对我不知道的功能负载的影响。

现在的问题是我的上传方法中的 submit 调用触发了 ko 绑定(bind)的 saveProfileChanges,它再次调用我的上传函数,令人作呕。有没有办法可以忽略 ko 绑定(bind),只进行本地调用 submit ?我不太喜欢的替代方案是在忙于上传时在 View 模型中设置一个标志,因此 saveProfileChanges 将简单地返回而不做任何进一步的操作,直到我的上传完成。

最佳答案

这实际上是一个 jQuery 问题而不是 KO。将您的提交调用更改为:

$("#userProfileForm")[0].submit();
// Change -----------^^^

例如,调用 form 元素的 submit 而不是 jQuery 的。 form 元素的函数不会再次触发submit 事件,但 jQuery 会。

我认为您的表单提交是在某些异步任务(例如上传文件)之后发生的,否则您只想让 saveProfileChanges 返回 true 到告诉 KO 允许默认操作(因为 KO 将默认自动阻止提交)。

这里演示了使用 jQuery 的 submit 时出现的问题:Live Copy

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<form action="http://google.com/search">
<input type="text" name="q" value="kittens">
<input type="submit" value="Send">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
(function() {
var counter = 0;

// Hook a handler to the form's submit event. Note that KO will
// use jQuery to do this if jQuery is on the page, so we'll do it
// via jQuery
$("form").on("submit", function(e) {
var form = this;

// Note that we got the event
++counter;
display("submit event received, counter = " + counter);

// Simulate asynchronous task
setTimeout(function() {
// We limit the number of times we'll re-fire
if (counter < 3) {
alert("submitting form using jQuery's submit function (counter = " + counter + ")");
$(form).submit();
} else {
alert("but now we'll submit it directly, not through jQuery");
form.submit();
}
}, 10);

// By default, KO will prevent the default, so do that
e.preventDefault();
});

function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})();
</script>
</body>
</html>

关于javascript - 如何选择性地忽略 knockout 'submit' 绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27500028/

25 4 0
文章推荐: javascript - CasperJS POST AJAX 不起作用
文章推荐: javascript - 将事件监听器添加到附加在 d3 中的
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com