函数中的拾取参数和使用原始参数的回调
Pickup argument in function and callback with original arguments
如何将回调传递给函数,并且该函数使用callee
需要的原始参数调用回调(但用结果替换第一个参数)?
我有这个例子:
this.createImage: function(base64, callback) {
var img = new Image();
img.src = base64;
img.onLoad = function() {
callback(this); // I also want to pass position here (this + arbitrary number of arguments)
}
}
this.addToCanvas: function(item, position) {
if(!this.isImage(item)) { // assume `isImage()` check if item is Image, & skips if true
var item = this.createImage(item, this.addToCanvas);
return;
}
item.position = position;
// Supposedly here I am certain that image is an Image() and not a
// base64 string
}
所以基本上我想知道我怎么能createImage
回调addToCanvas
而是通过原始position
,但item
取代加载的img
。
这里的想法是能够使用 Image
或 base64 String
调用addToCanvas()
,并且在需要时仍然能够在内部进行转换。
但是,我希望仍然能够将createImage()
与需要使用另一个(任意)数量的参数调用的其他函数重用。我想知道是否有可能不将上述功能耦合在一起。
我建议只使用本地函数。
如果数据已经是图像,则只需立即调用处理它的本地函数即可。 如果它还不是图像,则将其转换为图像,然后从回调调用本地函数。
由于本地函数可以访问传递给原始函数调用的所有参数,因此这解决了这部分问题,而无需执行任何特殊的参数传递。 这也是Javascript的一大功能(函数可以访问其所有父参数):
this.createImage = function (base64, callback) {
var img = new Image();
img.onLoad = function () {
callback(img);
}
img.src = base64;
}
this.addToCanvas = function (item, position) {
function addIt(img) {
// we know that img is an actual image here so you can process it now
img.position = position;
// other processing of the image here ...
}
if (!this.isImage(item)) {
// have to make it an image before addIt
this.createImage(item, addIt);
} else {
// already an image, can call addIt now
addIt(item);
}
}
您正在寻找部分参数应用程序。这是一种函数式编程技术:在纯JavaScript中,你会这样做:
var that = this; // necessary because this has another vaue inside the wrapper function
var item = this.createImage(item, function(x) {
return that.addToCanvas(x, position)
});
// here you are passing a wrapper function, that 'waits' for an x to be passed in order to call finally addToCanvas, with x and position.
img.onLoad = function() {
callback(this); // this goes into the above's x
}
使用像 underscore.js 这样的函数库同样的事情看起来会更优雅,如下所示:
var item = this.createImage(item, _.partial(this.addToCanvas, _, position));
相关文章:
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- 函数参数中的数据与指定变量之间的任何性能差异
- 使用Express捕获参数
- 参数变量出现ngTable指令问题
- AngularJS:我可以跳过函数参数回调吗
- 如何使用skip参数使用angular ui引导进行服务器端分页
- 要求未定义JS回调参数
- 我的jQuery插件参数没有正确启动,遇到了问题
- 我们可以用参数对象集合而不是原始数据来调用JavaScript collection.reduce()方法吗
- 将作用域绑定到事件处理程序,但保留原始参数
- 为什么Coderbyte.com's的Javascript模板喜欢返回函数的原始参数
- 如何将函数的参数重新分配回原始参数名称
- 函数中的拾取参数和使用原始参数的回调
- 从作为参数传入的数组中删除对象不会修改原始数组 (Angular)
- 添加新的第一个参数,然后应用原始参数
- 如何在_中使用原始参数.wrap '函数在下划线中
- Javascript: bind参数,但保留原始参数
- JavaScript Bookmarklet打开新窗口并传输原始页面的参数
- Javascript:在方法内部调用方法本身(带原始参数)
- 跨浏览器等效于 显式原始目标事件参数