在mootools中设置链是非常简单的。然而,使用Chain类作为mixin可能会涉及更多一点。
通常,它是为了链接基于Fx的类和方法而不是同步的。说你有一个补间效应,其中有link: chain
在发挥作用,你可以在.chain(function() {})
这个实例之后做点别的事情。
the callChain example作为一个独立单位是很好,很容易,但它提供了很少的时间控制。
然后是线性时间轴方法。在你的情况下,你的第一个回调在20ms之后运行,1980ms之后第二个,第三个运行在第二个回合之后1680ms等等。如果你把事情链接起来,以便每一个连续的步骤都会调用下一个步骤,那么你需要考虑这一点,并且实际上将时间传递给两个操作之间的等待时间。
另一种方式是按照从一开始就完成的方式推迟它们。
我在这里精简前一点了个去:http://jsfiddle.net/dimitar/mpzzq/
(function(){
Chain.implement({
slowChain: function(duration){
// console.log(duration);
this.callChain.delay(duration === null ? 500 : duration, this);
}
});
var db = $(document.body);
var fixBody = function(cn, delay) {
console.log(arguments);
db.addClass(cn);
console.log(cn, delay);
if (this.$chain.length) {
this.slowChain(delay || 0);
}
};
var myChain = new Chain(),
funcs = [{
fn: fixBody,
args: ["load"],
delay: 1980
}, {
fn: fixBody,
args: ["load-two"],
delay: 700
}, {
fn: fixBody,
args: ["load-three"],
delay: 2000
}, {
fn: fixBody,
args: ["load-four"],
delay: 0
}];
myChain.chain(
funcs.map(function(el) {
el.args.push(el.delay);
return el.fn.bind.apply(el.fn, [myChain].concat(el.args));
})
);
document.getElement("button").addEvents({
click: function() {
myChain.slowChain(20);
}
});
})();
所以在我的funcs中的对象数组我定义FUNC回调的参数传递和延迟。请记住,func本身已将this
作用域设置为链实例,并自我调用链上的下一个作用域,但您可以轻松地对此进行修改并使用它。
希望它给你一些想法。
这里是取2带装饰功能的调用上的延迟链:那
// function decorator.
Function.implement({
chainDelay: function(delay, bind) {
// allows you to set a delay for chained funcs and auto call stack (if bind is a chain instance)
var self = this,
args = (arguments.length > 2) ? Array.slice(arguments, 2) : null;
return function() {
setTimeout(function() {
self.apply(bind, args.concat(Array.from(arguments)));
if (bind && bind.$chain && bind.$chain.length)
bind.callChain.call(bind);
}, delay);
}
},
justChain: function(bind) {
// runs a chained func when due and auto calls stack for next (if bind is a chain instance and avail)
var self = this, args = (arguments.length > 1) ? Array.slice(arguments, 1) : null;
return function() {
self.call(bind, args);
if (bind && bind.$chain && bind.$chain.length)
bind.callChain.call(bind);
}
}
});
var moo = new Chain();
moo.chain(
// some delayed ones.
(function(what) {
console.log(what);
}).chainDelay(3000, moo, "hi"),
(function(what, ever) {
console.log(what, ever);
}).chainDelay(3000, moo, "there", "coda"),
(function(what) {
new Element("div[id=foo][html=" + what +"]").inject(document.body);
}).chainDelay(1000, moo, "mootools FTW!"),
// regular ones here for good measure!
(function() {
document.id("foo").setStyle("color", "red")
}).justChain(moo),
(function() {
document.id("foo").setStyle("background-color", "blue")
})
);
moo.callChain();
例如:http://jsfiddle.net/dimitar/Y4KCB/4/
非常感谢您抽出宝贵演示和解释的时间。我会仔细看看您创建的示例,并尝试查看哪种方法可以提供最佳性能。再次感谢。 :) – Dave
检查这取2,我想通过功能装饰/方法更好的方式。 HTTP://的jsfiddle。net/dimitar/Y4KCB/ –
我继续感谢您关注此事。这当然是比我原先想象的更复杂的问题,我很乐意收到您的意见。干杯。 – Dave