简体   繁体   English

事件触发功能的返回值

[英]Return value of event triggered function

I'm simply implementing a function that is called after a button is clicked. 我只是在实现一个在单击按钮后调用的函数。 The function works fine, but i'm not capable of making it return a value and assign it to a variable. 该函数工作正常,但我无法使其返回值并将其分配给变量。

I would like to call the function play once the button is clicked, and then return the values (as shown in the code) to a variable, in order to make them accessible for future uses. 我想在单击按钮后调用函数play ,然后将值(如代码中所示)返回到变量,以使它们可供将来使用。

I've already implemented all I need (i'm messing around with the web audio api) and it works fine, the test1 variable "embeddeds" the osc and lfo variables and i'm able to access them outside the function. 我已经实现了我所需要的所有东西(我正在使用Web音频api搞乱),并且工作正常, test1变量“嵌入”了osclfo变量,并且我可以在函数外部访问它们。

var ac = new AudioContext();

function play(){
     var osc = ac.createOscillator();
     var lfo = ac.createOscillator();
     osc.frequency.value=1000;
     console.log("Clicked!!");
     returnedObject={};
     returnedObject["value1"] = osc;
     returnedObject["value2"] = lfo;
     return returnedObject;
};

var test1= play();
var test= document.getElementById("mybtn").addEventListener("click", play);

The test1 variable contains what i need, but the test variable doesn't. test1变量包含我需要的东西,但test变量没有。

How can i assign to a variable the returned object of a function after it's been called by an event? 事件调用函数后,如何将返回的函数对象分配给变量?

What i'm getting right now if i use test.value1 is an undefined error, this makes me think that the assignment of the variable failed. 如果我使用test.value1我现在得到的是一个undefined错误,这使我认为变量分配失败。

Answer: 回答:

You can do this, but you have to consider that the value is undefined until the button is clicked. 您可以执行此操作,但是必须考虑到在单击按钮之前该值是undefined的。

 var ac = new AudioContext(); function play(){ var osc = ac.createOscillator(); var lfo = ac.createOscillator(); console.log("Clicked!!"); returnedObject={}; returnedObject["value1"] = osc; returnedObject["value2"] = lfo; return returnedObject; }; var test; document.getElementById("mybtn").addEventListener("click", () => (test = play())); 
 <button id="mybtn">click me</button> 


In order to perform functions with the data you probably want to create a middle function that takes care of whatever work you want done: 为了对数据执行功能,您可能想要创建一个中间功能,该功能可以处理您想要完成的所有工作:

 var ac = new AudioContext(); function play(){ var osc = ac.createOscillator(); var lfo = ac.createOscillator(); console.log("Clicked!!"); returnedObject={}; returnedObject["value1"] = osc; returnedObject["value2"] = lfo; return returnedObject; }; function middle(fn) { return function() { let data = fn(); //do something console.dir(data); } } document.getElementById("mybtn").addEventListener("click", middle(play)); 
 <button id="mybtn">click me</button> 


Alternatively you can create a Constructor that holds onto the data, thus allowing you to add methods to the Constructor for manipulation at a later time: 另外,您可以创建一个保存数据的构造函数,从而使您可以向该构造函数添加方法以供以后使用:

 function Player() { let proto = {}; proto.ac = new AudioContext(); proto.data = []; proto.play = function() { var osc = proto.ac.createOscillator(); var lfo = proto.ac.createOscillator(); proto.data.push({ value1: osc, value2: lfo }); proto.latest = proto.data[proto.data.length-1]; console.log("Clicked!!", proto.latest); }; return proto; } const myPlayer = new Player(); document.getElementById("mybtn").addEventListener("click", myPlayer.play); 
 <button id="mybtn">click me</button> 

addEventListener , by design, is meant to don't return anything at all (thanks @AmitJoki for mentioning that) as you can read in the MDN docs . addEventListener设计, addEventListener旨在完全不返回任何内容(感谢@AmitJoki提及) ,您可以在MDN docs中阅读

The relevant part is (excerpt of this section ) 相关部分是( 本节节选)

Event listeners only take one argument, the Event Object, which is automatically passed to the listener, and the return value is ignored 事件侦听器仅采用一个参数,即事件对象,该对象会自动传递给侦听器,并且返回值将被忽略

The reason behind that is that addEventListener is just meant to register an event , not to handle the result of it. 其背后的原因是addEventListener仅用于注册事件 ,而不是处理事件的结果。

If you want to assign the result to the global variable test , you should just do that inside your play callback. 如果要将结果分配给全局变量test ,则应 play回调中执行此操作。

I will suggest you to use closure instead. 我建议您改用闭包。 Try something like this. 尝试这样的事情。

 // closure
        function audioControl() {

            var ac = new AudioContext();
            var props = {
                value1: ac.createOscillator(),
                value2: ac.createOscillator()
            };
            // function play
            function play() {
                osc.frequency.value = 1000;
                console.log("Clicked!!");
                props.value1 = "_modified_value";
                props.value2 = "_modified_value";
            }
            return {
                props: props,
                play: play
            }
        };

        var test1 = audioControl();
        var test = document.getElementById("mybtn").addEventListener("click", test1.play);

        // now you can get values anywhere anytime using
        // -- test1.props.value1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM