[英]Return this inside Ajax call of JQuery plugin for chaining
我正在尝试链接我编写的插件的多个调用。 该插件本身有两个可能的Ajax调用-到内容存储服务以及车把模板。 我对两者都进行了缓存,但是在第一次加载时,卡的顺序通常会发生变化,这是因为某些调用所花费的时间比其前辈更长。 结果,卡的顺序改变,这在内容层次上是有问题的。 在此示例中,我正在加载标记为研究和播客的卡片。
我按如下方式调用插件:
$('#research').getCards({
category: 'research',
}).getCards({
category: 'podcast'
});
插件很大,所以我只发布最后一个Ajax调用(这是我要返回的地方)。 从服务中获取数据后,将调用fetchTemplate函数,计数器为0,length为初始化函数时card_data的长度。 我希望此函数递归直到card_data数组中的每个项目都打印出一张卡,然后它应该返回此值以允许对getCards的下一次调用。
$.fn.getCards = function(options) {
var defaults = {
target: this,
category: '',
},
settings = $.extend({}, defaults, options);
function fetchTemplate(card_data, counter, length) {
counter++;
var cardTemplate = '';
if (localStorage[cardTemplate] && settings.localStorageSupport) {
printCard(localStorage[cardTemplate], card_data[counter - 1]);
if (counter !== length) {
fetchTemplate(card_data, counter, length);
}
} else {
$.ajax({
url: '/templates/cards/' + cardTemplate + '.hbs.js',
type: 'GET',
dataType: 'text',
success: function(data) {
localStorage.setItem(cardTemplate, data);
printCard(data, card_data[counter - 1]);
return this // this is when I want to fire my chained call
if (counter !== length) {
fetchTemplate(card_data, counter, length);
}
}
});
}
}
};
我尝试过关闭,但没有用。 我也尝试过return settings.target
。 最后,我尝试包装整个插件以return this.each
但这在Ajax请求完成之前每次触发时均不起作用。 我知道我可以只通过一次调用getCards来重写插件,以调用一组类别,但是我不希望重写我的所有逻辑。
您可以使用.queue()
和.promise()
按顺序执行异步任务。
设置context
的$.ajax()
调用this
方法内,用于this
是内元件.then()
在定义属性.data()
的this
集合到函数内的阵列和填充结果阵列异步任务。 设置Chain .then()
以从$.fn.getCards()
调用中获取结果, this
将被设置为原始jQuery对象,并且异步任务的结果将可以通过this
.data()
访问。 然后,您可以再次调用.getCards()
,重复该过程。
$.fn.getCards = function(options) { var el = this; if (!this.data().results) { this.data().results = []; } return this.queue("cards", $.map(options, function(item) { return function(next) { return $.Deferred(function(dfd) { setTimeout(function() { dfd.resolveWith(el, [item]) }, 1000) }) .then(function(data) { this.data().results.push(data); return; }) .then(next) } })).dequeue("cards").promise("cards") } $("body") .getCards([1,2,3]) .then(function() { console.log(this.data().results, this.get(0).tagName === "BODY"); return this.getCards([4,5,6]) }) .then(function() { console.log(this.data().results, this.get(0).tagName === "BODY"); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.