This piece of code was provided as a working solution to a previous question on flow control:
// an object to maintain a list of functions that can be called in sequence
// and to manage a completion count for each one
function Sequencer() {
this.list = [];
this.cnt = 0;
}
Sequencer.prototype.add = function(/* list of function references here */) {
this.list.push.apply(this.list, arguments);
}
Sequencer.prototype.next = function() {
var fn = this.list.shift();
if (fn) {
fn(this);
}
}
Sequencer.prototype.increment = function(n) {
n = n || 1;
this.cnt += n;
}
// when calling .decrement(), if the count gets to zero
// then the next function in the sequence will be called
Sequencer.prototype.decrement = function(n) {
n = n || 1;
this.cnt -= n;
if (this.cnt <= 0) {
this.cnt = 0;
this.next();
}
}
// your actual functions using the sequencer object
function test_1(seq, arg1, arg2, arg3) {
seq.increment();
// do something with arg1, arg2 and arg3
seq.decrement();
}
function test_2(seq) {
seq.increment();
// do something
seq.decrement();
}
function test_3(seq) {
seq.increment();
// do something
seq.decrement();
}
// code to run these in sequence
var s = new Sequencer();
// add all the functions to the sequencer
s.add(test_1, test_2, test_3);
// call the first one to initiate the process
s.next();
How can I pass arguments to test_1()
when adding the function to s
? For example (which obviously doesn't work):
s.add(test_1(10,'x',true), test_2);
Thanks
If the order was different, ie test_1(arg1, arg2, arg3, seq)
, you could use .bind
:
s.add(test_1.bind(null, 10,'x',true) , test_2, test_3);
If you can't change the the order, pass an other function which in turn calls test_1
:
s.add(function(seq) { test_1(seq, 10,'x',true); }, test_2, test_3);
您可以使用Function.arguments
访问函数的给定参数。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.