var Stuff = (function() {
return {
getId: function (id) {
return document.getElementById(id);
},
attr: function (ele, attr, newVal) {
var newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrslen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
for (var i = 0; i < attrslen; i++)
if (attr[i].nodeName === attr) result = attr[i].nodeValue;
}
return result;
}
}
}
})();
用这个 html:
<div id="foo" data-stuff="XYZ">Test Div</div>
当前的实现:
(function ($) {
console.log(
$.attr($.getId('foo'), 'data-stuff') // XYZ
);
})(Stuff);
我如何重写上面的库以使其像下面这样链接?
(function ($) {
console.log(
$.getId('foo').attr('data-stuff') // XYZ
);
})(Stuff);
最佳答案
专门从您的代码构建,您可以这样做:
示例: http://jsfiddle.net/patrick_dw/MbZ33/
var Stuff = (function() {
return {
elem:null,
getId: function (id) {
this.elem = document.getElementById(id);
return this;
},
attr: function (attr, newVal) {
var newVal = newVal || null;
var ele = this.elem;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrslen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
for (var i = 0; i < attrslen; i++)
if (attr[i].nodeName === attr) result = attr[i].nodeValue;
}
return result;
}
}
}
})();
这添加了一个 elem
属性,用于存储 getId
的结果。 getId
返回this
,这是包含所有方法的Stuff
引用的对象。因此,您可以直接从返回的对象调用 attr
。
我想您会希望在设置属性时包含 this
的 attr
的返回值,以便链接可以继续。
关于javascript - 将 javascript 库转换为链式方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4434042/