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)
}