Javascript Class Return Array, Create Library Like Jquery
I'm creating javascript library like jQuery, I have successfully adding prototype html() but if I call it with $(selector) it return object like {'el' : [array]} and if change in f
Solution 1:
window.$ = function(selector) {
var x = [];
x = document.querySelectorAll(selector);
console.log(x);
return x;
};
NodeList.prototype.html = function(str) {
console.log(this);
this.forEach(function(el){
el.innerHTML = str;
});
}
console.log($('#test').html('BBBBB'))
<divid="test"></div>
I extended the html method inside the NodeList array. tell me if it can fit you.
Solution 2:
finally it solved by looking Zepto
source code, the magic to convert object to array is you have to create $.prototype.splice
, it copied from the Array.splice
// only load if no jQuery on the pageif (window.$ === undefined) window.$ = (function () {
var $, zepto = {}, emptyArray = [];
functionZ(dom, selector) {
var i, len = dom ? dom.length : 0;
for (i = 0; i < len; i++) this[i] = dom[i];
this.length = len;
this.selector = selector || '';
}
Z.prototype = {
splice: emptyArray.splice,
forEach: emptyArray.forEach,
html: function (str) {
this.forEach(function (el) {
el.innerHTML = str;
});
}
};
zepto.Z = function (dom, selector) {returnnewZ(dom, selector);};
zepto.init = function (selector, context) {
if (!selector) return zepto.Z();
var dom = document.querySelectorAll(selector);
return zepto.Z(dom, selector);
};
$ = function (sel, ctx) {return zepto.init(sel, ctx); };
return $;
})();
$('.test').html('DDDDD');
console.log($('.test'));
<divclass="test"> AAAA </div><divclass="test"> BBBB </div><divclass="test"> CCCC </div>
Post a Comment for "Javascript Class Return Array, Create Library Like Jquery"