长话短说,您可以通过使用wp.media.attachment()
作用只要此附件已由另一个脚本或wp.media()
弹出窗口。
如果尚未加载数据,可以使用.fetch()
方法,因为它是Backbone.Collection
. 这是一个Collection
因为附件中可能有多个选定文件。
// preload your attachment
wp.media.attachment(ID).fetch().then(function (data) {
// preloading finished
// after this you can use your attachment normally
wp.media.attachment(ID).get(\'url\');
});
进行预加载的简单方法:
function preloadAttachment(ID, callback) {
// if it doesn\'t have URL we probably have to preload it
if (wp.media.attachment(ID).get(\'url\')) {
wp.media.attachment(ID).fetch().then(function () {
callback(wp.media.attachment(ID);
});
return;
}
callback(wp.media.attachment(ID));
}
// USAGE:
preloadAttachment(10, function (attachment) {
console.log(attachment.get(\'url\'));
console.log(wp.media.attachment(10).get(\'url\')); // this also works
})
这就是您希望在一个AJAX请求中预加载多个附件的方式。
// An array of attachments you may want to preload
var attachment_ids = [10, 11, 12, 13];
wp.media.query({ post__in: attachment_ids })
.more()
.then(function () {
// You attachments here normally
// You can safely use any of them here
wp.media.attachment(10).get(\'url\');
})
请注意以下事实:
wp.media.query()
已分页。如果您需要一个健壮的解决方案来加载大量的附件,那么您应该使用
hasMore()
and more()
methods.
免责声明:
我在发现wp.media.query
但它有一个惩罚,即对每个预加载的附件发出一个请求。但它也有一个很好的特性——如果所有需要预加载的附件都已经处于fetched状态,它不会发出任何请求。
function preloadMultipleAttachments(attachment_ids) {
// I\'d rather use Promise.all() here but they do not work with
// jQuery deferreds :/
if (jQuery.when.all===undefined) {
jQuery.when.all = function(deferreds) {
var deferred = new jQuery.Deferred();
$.when.apply(jQuery, deferreds).then(
function() {
deferred.resolve(Array.prototype.slice.call(arguments));
},
function() {
deferred.fail(Array.prototype.slice.call(arguments));
});
return deferred;
}
}
return jQuery.when.all(
attachment_ids.filter(function (attachment_id) {
return ! wp.media.attachment(attachment_id).get(\'url\');
}).map(function (id) {
return wp.media.attachment(id).fetch();
})
);
},