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)
}
复制代码
var wait = function(){
var task = function(){
console.log('执行完成');
}
setTimeout(task,2000)
}
wait();
复制代码
新增需求:要在执行完成以后进行某些特别复杂的操做,代码可能会不少,并且分好几步
functionwaitHandle(){
var dtd = $.Deferred(); //建立一个deferred对象
var wait = function(dtd){ // 要求传入一个deferred对象
var task = function(){
console.log("执行完成");
dtd.resolve(); //表示异步任务已完成
//dtd.reject() // 表示异步任务失败或者出错
};
setTimeout(task,2000);
return dtd;
}
//注意,这里已经要有返回值
returnwait(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()
functionwaitHandle(){
var dtd = $.Deferred();
var wait = function(){
var task = function(){
console.log('执行完成');
dtd.resolve();
}
setTimeout(task,2000)
return dtd.promise(); //注意这里返回的是promise,而不是直接返回deferred对象
}
returnwait(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捕获异常
两种异常状况:
程序逻辑异常
业务以内,reject()等状况
处理方案 在reject("图片路径错误")中把信息传出去,能够经过'.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 复制代码
<ul id = "list">
<li class='item'>Item 1</li>
</ul>
复制代码
简单实现算法
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);
}
} elseif (typeof val === 'number') {
ret = new Array(val);
for (i = 0; i < val; i++) {
ret[i] = render(i + 1, i);
}
} elseif (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
}
复制代码
import Todo from './components/todo/index.js';
class App extends Component {
render() {
return (
<div className="App">
<Todo></Todo>
</div>
);
}
}
export default App;
复制代码
src => components => todo
import React, { Component } from 'react'
class Todo extends Component {
constructor(props) {
super(props)
}
render() {
return (
<p> this is todo component </p>
)
}
}
export default Todo
复制代码
todolist Demo2
list => todo => index.js
import React, { Component } from 'react'
class List extends Component{
constructor(props){
super(props)
}
render() {
const list = this.props.data
return (
<ul>
{
list.map((item,index) =>{
return <li key={index}>{item}</li>
})
}
</ul>
)
}
}
export default List
复制代码
必须加key
todo.js
import React, { Component } from 'react'
import List from './list/index.js';
import Input from './input/index.js';
class Todo extends Component {
constructor(props) {
super(props)
this.state = {
list:[]
}
}
render() {
return (
<div>
<Input addTitle={this.addTitle.bind(this)}/>
<List data={this.state.list} />
</div>
)
}
//主动添加list
addTitle(title){
const currentList = this.state.list //获取当前list
this.setState(
{
list:currentList.concat(title)
}
)
}
}
export default Todo
复制代码