我正在寻找一种完成某项任务的方法,即从
jQuery.when.apply( null, promiseArray ).done(...)
自
when( promiseArray ).done(...)
您可能知道,.bind()
可以习惯于创建默认参数之类的东西,也可以做一些非常漂亮的事情。例如,而不是总是调用
var toStr = Object.prototype.toString;
// ...
toStr.call([]) // [object Array]
我们可以像
var toStr = Function.prototype.call.bind( Object.prototype.toString );
toStr([]) // [object Array]
这是相当酷的(即使有这样的.bind()
调用性能损失,我知道并且我知道),但我无法真正完成 jQuerys .when
调用。如果你得到了未知数量的 promise 对象,你通常会将它们推送到一个数组中,然后能够将它们传递到.when
中,就像我上面的第一个代码片段一样。
到目前为止,我正在这样做:
var when = Function.prototype.apply.bind( $.when );
现在我们可以像
when( null, promiseArray ).done(...)
这有效,但我也想摆脱每次都明确传入null
的需要。所以我尝试了
var when = Function.prototype.apply.bind( $.when.call.bind( null ) );
但这让我感到震惊:
"TypeError: Function.prototype.apply called on incompatible null"
我想我现在坐得太久了,不能再直截了当地思考了。感觉有一个简单的解决方案。我不想使用任何其他功能来解决此问题,我绝对更喜欢使用 .bind()
的解决方案。
在此处查看完整示例:http://jsfiddle.net/pp26L/
这应该有效:
when = Function.prototype.apply.bind( $.when, null);
您只需绑定(或咖喱,如果您愿意).bind
的第一个参数并将其修复为 null
。
小提琴。
bind
接受可变数量的参数,因此您可以部分应用方法。因此,而不是:
var when = Function.prototype.apply.bind( $.when );
这样做:
var when = Function.prototype.apply.bind( $.when , null );
并更新了jsfiddle:http://jsfiddle.net/pp26L/2/