简体   繁体   English

在js的as3回调中传递参数的最佳方法是什么

[英]what is the best way to pass parameters in an as3 callback from js

I've been wondering this question for a while: in as3, when you call a method or a function, you pass it paramameters in this way: 我一直想知道这个问题有一段时间:在as3中,当您调用方法或函数时,您可以通过以下方式将其传递给参数:

method(param1, param2); 方法(param1,param2);

but what happends when your method requires a bunch of them? 但是当您的方法需要大量这些方法时会发生什么? Instead of passing them all like: method(p1,p2,p3,p4,p5,p6,p7,p8); 而不是像这样传递它们:method(p1,p2,p3,p4,p5,p6,p7,p8);

a better way is to create a model object that contains all those params, and you just pass the whole model: 更好的方法是创建一个包含所有这些参数的模型对象,然后只需传递整个模型即可:

model : Model = new Model();
model.p1 = "something";
model.p2 = "another something";
...
method(model);

this way you can ensure that method() is called with the right number and type of parameters. 这样,您可以确保使用正确数量和类型的参数调用method()。 but also avoiding use of a huge amount of parameters. 而且还避免使用大量参数。

however, when using JS callbacks, two problems arises: passing the whole list of parameters: method(..., p8); 但是,当使用JS回调时,会出现两个问题:传递整个参数列表:method(...,p8); is a bad way as always, but at least I have a strict way of forcing the callback to be called with the correct parameters. 和往常一样是一种不好的方法,但是至少我有一种严格的方法来强制使用正确的参数调用回调。 the other solution would be passing a model, but I can't pass from js a defined as3 Object, the most I can do is to pass a js object: 另一个解决方案是传递一个模型,但是我无法从js传递一个定义为as3的对象,我能做的最多就是传递一个js对象:

$("as3Component").as3Callback({p1 : "something", p2 : "another something"});

and from as3: 从as3:

as3Callback(params : Object)
{
    trace(params.p1); 
}

however, I cannot have a strict way to know wich parameters I can receive, so Object could contain anything. 但是,我无法采用严格的方式来知道可以接收的参数,因此Object可以包含任何内容。

so my question is, what is the best way to pass a huge amount of parameters from js to as3 without having a single method with lots of parameters and not having this "magic" object that could contain any attributes on it. 所以我的问题是,最好的方法是从js到as3传递大量参数,而又没有一个具有很多参数的方法,并且没有这个可以包含任何属性的“魔术”对象。 thx!. 谢谢!。

Passing an object as a parameter is absolutely fine. 将对象作为参数传递绝对是可以的。

All you need is some sort of validation of the parameters, for example: 您只需要对参数进行某种形式的验证,例如:

function as3Callback(params : Object):void
{
    params.p1 = params.p1 || "default value for p1";
    params.p2 = params.p2 || "default value for p2";
    params.p3 = params.p3 || "default value for p3";
    params.p4 = params.p4 || "default value for p4";

    ...

    trace(params.p1); 
}

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

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