国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

JavaScript 異步方法隊列鏈實現代碼分析

2024-05-06 12:37:05
字體:
來源:轉載
供稿:網友

在《javascript設計模式》中對這種方法作了比較詳細的描述,實現方法的鏈式調用,只須讓在原型中定義的方法都返回調用這些方法的實例對象的引用即可,看看書中的這段代碼:
代碼如下:
(function() {
function _$(els) {
this.elements = [];
for (var i = 0, len = els.length; i < len; ++i) {
var element = els[i];
if (typeof element == 'string') {
element = document.getElementById(element);
}
this.elements.push(element);
}
};
_$.prototype = {
each: function(fn) {
for ( var i = 0, len = this.elements.length; i < len; ++i ) {
fn.call(this, this.elements[i]);
}
return this;
},
setStyle: function(prop, val) {
this.each(function(el) {
el.style[prop] = val;
});
return this;
},
show: function() {
var that = this;
this.each(function(el) {
that.setStyle('display', 'block');
});
return this;
},
addEvent: function(type, fn) {
var add = function(el) {
if (window.addEventListener) {
el.addEventListener(type, fn, false);
}
else if (window.attachEvent) {
el.attachEvent('on'+type, fn);
}
};
this.each(function(el) {
add(el);
});
return this;
}
};
window.$ = function() {
return new _$(arguments);
};
})();

可以看到,每個方法都以”return this”結束,這就會將調用方法的對象傳遞給鏈上的下一個方法。但是,如果我們要操作的數據是通過異步請求來獲得的,如何保持方法的鏈式調用呢?Dustin Diaz為我們提供了一種方法來保證方法的鏈式調用,他也是《javascript設計模式》一書的作者之一。
他首先構建了一個Queue對象,即:
代碼如下:
function Queue() {
// store your callbacks
this._methods = [];
// keep a reference to your response
this._response = null;
// all queues start off unflushed
this._flushed = false;
}
Queue.prototype = {
// adds callbacks to your queue
add: function(fn) {
// if the queue had been flushed, return immediately
if (this._flushed) {
fn(this._response);
// otherwise push it on the queue
} else {
this._methods.push(fn);
}
},
flush: function(resp) {
// note: flush only ever happens once
if (this._flushed) {
return;
}
// store your response for subsequent calls after flush()
this._response = resp;
// mark that it's been flushed
this._flushed = true;
// shift 'em out and call 'em back
while (this._methods[0]) {
this._methods.shift()(resp);
}
}
};

然后用它作為工具構建我們的異步方法隊列鏈。有了這個工具,就可以很方便的構建一個從服務器端獲取內容并將其附加到選擇器中的jQuery plugin。
代碼如下:
(function($) {
$.fn.fetch = function(url) {
var queue = new Queue;
this.each(function() {
var el = this;
queue.add(function(resp) {

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 临湘市| 佛冈县| 车险| 防城港市| 大田县| 桂林市| 盈江县| 聊城市| 长葛市| 霍城县| 调兵山市| 罗城| 文安县| 额敏县| 高邮市| 敖汉旗| 亚东县| 仲巴县| 霍林郭勒市| 望都县| 永定县| 蚌埠市| 玉屏| 邵东县| 怀柔区| 五华县| 塘沽区| 平阳县| 南昌县| 东宁县| 扎鲁特旗| 商城县| 乌拉特后旗| 广南县| 荔浦县| 房山区| SHOW| 东至县| 乐陵市| 双柏县| 蓝田县|