[英]Raising and Subscribing event in JavaScript
I don't know if this is even possible. 我不知道这是否有可能。 I have a javascript that simply serializes the form on a page and saves it to the server on button click
我有一个javascript,只需将页面上的表单序列化,然后单击按钮即可将其保存到服务器
// dispatcher script
$(function(){
$("#btn").click(function(){
// how to raise event here before save that another script can subscribe
var data = $("#myform").serialize();
//Save data here using jquery Ajax
})
})
now on the same page there is one more javascript. 现在,在同一页面上还有一个Javascript。 and this javascript needs to do something before save.
并且此javascript需要在保存之前执行某些操作。
// listener script
$(function(){
// in this script i want to subscribe to event and do something when event is raised
})
Is there a way to raise event from one javascript and subscribe in other? 有没有一种方法可以从一个JavaScript引发事件并在其他javascript中进行订阅?
Note: for valid reasons i cannot combine both scripts into one 注意:出于有效的原因,我无法将两个脚本合并为一个
I looked at sample here however in my case which element subscriber would be listening on? 我在这里查看了示例,但是在我的情况下,哪个元素订户将收听? Assume Listener script does not know
btn
. 假设侦听器脚本不知道
btn
。
You may do like : 您可能会喜欢:
$(function(){ const btn = $('#btn'); btn.on('click',() =>{ console.log('from one file'); $(window).trigger('custom'); }) }); $(function(){ const btn = $('#btn'); $(window).on('custom',() =>{ console.log('from second file') }) })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="button" id="btn" value="Click me"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.