var $p = $("p")
$p.css("font-size","40px") //css是原型方法
console.log($p.html()) //html是原型方法
var $div1 = $("#div1")
$div1.css("color","blue") //css是原型方法
console.log($div1.html()) //html是原型方法
zepto如何使用原型
//空对象
var zepto = {}
zepto.init = function(){
//源码中,这里的处理情况比较复杂。但因为是本次只是针对原型,因此这里就弱化了
var slice = Array.prototype.slice
var dom = slice.call(document.querySelectorAll(selector))
return zepto.Z(dom,selector)
}
//即使用zepto时候的$
var $ = function(selector){
return zepto.init(selector)
}
//这就是构造函数
function Z(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 || ""
}
zepto.Z = function(dom, selector) {
return new Z(dom, selector)
}
(function(window) {
var zepto = {};
function Z(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 || "";
}
zepto.Z = function(dom, selector) {
return new Z(dom, selector);
}
zepto.init = function(selector) {
var slice = Array.prototype.slice;
var dom = slice.call(document.querySelectorAll(selector));
return zepto.Z(dom, selector);
}
var $ = function(selector) {
return zepto.init(selector);
}
window.$ = $;
$.fn = {
css: function(key, value) {
console.log(key, value);
},
html: function() {
return "html";
}
}
Z.prototype = $.fn
})(window)
jquery如何使用原型
var jQuery = function(selector){
//注意new关键字,第一步就找到了构造函数
return new jQuery.fn.init(selector);
}
//定义构造函数
var init = jQuery.fn.init = function(selector){
var slice = Array.prototype.slice;
var dom = slice.call(document.querySelectorAll(selector));
var i,len=dom?dom.length:0;
for(i = 0;i原型的扩展性
var wait = function(){
var task = function(){
console.log("执行完成");
}
setTimeout(task,2000)
}
wait();
新增需求:要在执行完成之后进行某些特别复杂的操作,代码可能会很多,而且分好几步
function waitHandle(){
var dtd = $.Deferred(); //创建一个deferred对象
var wait = function(dtd){ // 要求传入一个deferred对象
var task = function(){
console.log("执行完成");
dtd.resolve(); //表示异步任务已完成
//dtd.reject() // 表示异步任务失败或者出错
};
setTimeout(task,2000);
return dtd;
}
//注意,这里已经要有返回值
return wait(dtd);
}
//使用
var w = waithandle()
w.then(function(){
console.log("ok1");
},function(){
console.log("err2");
})
.then(function(){
console.log("ok2");
},function(){
console.log("err2");
})
//还有w.wait w.fail
总结:dtd的API可分成两类,用意不同
第一类:dtd.resolve 、 dtd.reject
第二类:dtd.then、dtd.done、dtd.fail
这两类应该分开,否则后果严重!
可以在上面代码中最后执行dtd.reject()试一下后果
使用dtd.promise()
function waitHandle(){
var dtd = $.Deferred();
var wait = function(){
var task = function(){
console.log("执行完成");
dtd.resolve();
}
setTimeout(task,2000)
return dtd.promise(); //注意这里返回的是promise,而不是直接返回deferred对象
}
return wait(dtd)
}
var w = waitHandle(); //promise对象
$.when(w).then(function(){
console.log("ok1");
},function(){
console.log("err1");
})
//w.reject() //w.reject is not a function
监听式调用:只能被动监听,不能干预promise的成功和失败
可以jQuery1.5对ajax的改变举例
说明如何简单的封装、使用deferred
说明promise和Defrred的区别
要想深入了解它,就需要知道它的前世今生
Promise的基本使用和原理
基本语法回顾
fucntion loadImg() {
var promise = new Promise(function(resolve,reject) {
var img = document.getElementById("img")
img.onload = function(){
resolve(img)
}
img.onerror = function(){
reject()
}
})
return promise
}
var src = ""
var result = loadImg(src)
result.then(function() {
console.log(1, img.width)
return img
}, fucntion() {
console.log("error 1")
}).then(function(img) {
console.log(1, img.width)
})
异常捕获
规定:then只接受一个函数,最后统一用catch捕获异常
var src = ""
var result = loadImg(src)
result.then(function() {
console.log(1, img.width)
return img
}).then(function(img) {
console.log(1, img.width)
}).catch(function(ex) {
//最后统一捕获异常
console.log(ex)
})
多个串联
var scr1 = "https://www.imooc.com/static/img/index/logo_new.png";
var result1 = loadImg(src1);
var src2 = "https://www.imooc.com/static/img/index/logo_new1.png";
var result2 = loadImg(src2);
result1.then(function(img1) {
console.log("第一个图片加载完成", img1.width);
return result2; //重要
}).then(function(img2) {
console.log("第二个图片加载完成", img2.width);
}).catch(function(ex) {
console.log(ex);
})
var div = document.createElement("div");
var item,result = "";
for(item in div){
result += "|" + item;
}
console.log(result);
//浏览器默认创建出来的DOM节点,属性是非常多的
//result
|align|title|lang|translate|dir|dataset|hidden|tabIndex|accessKey|draggable|spellcheck|autocapitalize|contentEditable|isContentEditable|inputMode|offsetParent|offsetTop|offsetLeft|offsetWidth|offsetHeight|style|innerText|outerText|onabort|onblur|oncancel|oncanplay|oncanplaythrough|onchange|onclick|onclose|oncontextmenu|oncuechange|ondblclick|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondragstart|ondrop|ondurationchange|onemptied|onended|onerror|onfocus|oninput|oninvalid|onkeydown|onkeypress|onkeyup|onload|onloadeddata|onloadedmetadata|onloadstart|onmousedown|onmouseenter|onmouseleave|onmousemove|onmouseout|onmouseover|onmouseup|onmousewheel|onpause|onplay|onplaying|onprogress|onratechange|onreset|onresize|onscroll|onseeked|onseeking|onselect|onstalled|onsubmit|onsuspend|ontimeupdate|ontoggle|onvolumechange|onwaiting|onwheel|onauxclick|ongotpointercapture|onlostpointercapture|onpointerdown|onpointermove|onpointerup|onpointercancel|onpointerover|onpointerout|onpointerenter|onpointerleave|nonce|click|focus|blur|namespaceURI|prefix|localName|tagName|id|className|classList|slot|attributes|shadowRoot|assignedSlot|innerHTML|outerHTML|scrollTop|scrollLeft|scrollWidth|scrollHeight|clientTop|clientLeft|clientWidth|clientHeight|attributeStyleMap|onbeforecopy|onbeforecut|onbeforepaste|oncopy|oncut|onpaste|onsearch|onselectstart|previousElementSibling|nextElementSibling|children|firstElementChild|lastElementChild|childElementCount|onwebkitfullscreenchange|onwebkitfullscreenerror|setPointerCapture|releasePointerCapture|hasPointerCapture|hasAttributes|getAttributeNames|getAttribute|getAttributeNS|setAttribute|setAttributeNS|removeAttribute|removeAttributeNS|hasAttribute|hasAttributeNS|toggleAttribute|getAttributeNode|getAttributeNodeNS|setAttributeNode|setAttributeNodeNS|removeAttributeNode|closest|matches|webkitMatchesSelector|attachShadow|getElementsByTagName|getElementsByTagNameNS|getElementsByClassName|insertAdjacentElement|insertAdjacentText|insertAdjacentHTML|requestPointerLock|getClientRects|getBoundingClientRect|scrollIntoView|scrollIntoViewIfNeeded|animate|computedStyleMap|before|after|replaceWith|remove|prepend|append|querySelector|querySelectorAll|webkitRequestFullScreen|webkitRequestFullscreen|scroll|scrollTo|scrollBy|createShadowRoot|getDestinationInsertionPoints|ELEMENT_NODE|ATTRIBUTE_NODE|TEXT_NODE|CDATA_SECTION_NODE|ENTITY_REFERENCE_NODE|ENTITY_NODE|PROCESSING_INSTRUCTION_NODE|COMMENT_NODE|DOCUMENT_NODE|DOCUMENT_TYPE_NODE|DOCUMENT_FRAGMENT_NODE|NOTATION_NODE|DOCUMENT_POSITION_DISCONNECTED|DOCUMENT_POSITION_PRECEDING|DOCUMENT_POSITION_FOLLOWING|DOCUMENT_POSITION_CONTAINS|DOCUMENT_POSITION_CONTAINED_BY|DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC|nodeType|nodeName|baseURI|isConnected|ownerDocument|parentNode|parentElement|childNodes|firstChild|lastChild|previousSibling|nextSibling|nodeValue|textContent|hasChildNodes|getRootNode|normalize|cloneNode|isEqualNode|isSameNode|compareDocumentPosition|contains|lookupPrefix|lookupNamespaceURI|isDefaultNamespace|insertBefore|appendChild|replaceChild|removeChild|addEventListener|removeEventListener|dispatchEvent
vdom如何应用,核心API是什么
介绍snabbdom
一个实现vdom的库,vue升级2.0借鉴了snabbdom的算法
var container = document.getElementById("container")
var vnode = h("div#container.two.classes", { on: { click: someFn } }, [
h("span", { style: { fontWeight: "bold" }, "This is bold" }),
"and this is just normal text",
h("a", { props: { href: "/foo" } }, "I"ll take you places")
])
//patch into empty DOM element - this modifies the DOM as a side effect
patch(container, vnode)
var newVnode = h("div#container.two.classes", { on: { click: anotherEventHandle } }, [
h("span", { style: { fontWeight: "normal", fontStyle: "italic" } }, "this is now italic type"),
"and this is still just normal text",
h("a", { props: { href: "/bar" } }, "I"ll take you places")
])
//send `patch` invocation
patch(vnode, newVnode); //Snabbdom efficiently updates the old view to the new state
function createElement(vnode) {
var tag = vnode.tag;
var attrs = vnode.attrs || {};
var children = vnode.children || [];
if (!tag) {
return null
}
//创建元素
var elem = document.createElement(tag);
//属性
var attrName;
for (attrName in atts) {
if (attrs.hasOwnProperty(attrName)) {
elem.setAttribute(attrName, attrs[attrName])
}
}
//子元素
children.array.forEach(childVnode => {
elem.appendChild(createElement(childVnode))
});
return elem;
}
//vm._l
function renderList(val,render) {
var ret, i, l, keys, key;
if (Array.isArray(val) || typeof val === "string") {
ret = new Array(val.length);
for (i = 0, l = val.length; i < l; i++) {
ret[i] = render(val[i], i);
}
} else if (typeof val === "number") {
ret = new Array(val);
for (i = 0; i < val; i++) {
ret[i] = render(i + 1, i);
}
} else if (isObject(val)) {
keys = Object.keys(val);
ret = new Array(keys.length);
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
ret[i] = render(val[key], key, i);
}
}
if (isDef(ret)) {
(ret)._isVList = true;
}
return ret
}
//分享
function invokeShare(data,callback){
_invoke("share",data,callback)
}
//登录
function invokeLogin(data,callback){
_invoke("login",data,callback)
}
//打开扫一扫
function invokeScan(data,callback){
_invoke("scan",data,callback)
}