This repository has been archived on 2023-08-30. You can view files and clone it, but cannot push or open issues/pull-requests.
bytedo
/
wcui
Archived
1
0
Fork 0

更新框架,内置Promise;组件支持slot

old
宇天 2018-05-02 20:44:04 +08:00
parent fe90703b85
commit a2d9603eaa
12 changed files with 730 additions and 561 deletions

View File

@ -40,14 +40,13 @@ const compileJs = (entry, output) => {
const compileCss = (entry, output) => {
let t1 = Date.now()
const { css } = scss.renderSync({ ...cssOpt, file: entry })
prefixer.process(css, { from: '', to: '' }).then(result => {
log(
'编译scss: %s, 耗时 %s ms',
chalk.green(entry),
chalk.yellow(Date.now() - t1)
)
fs.echo(result.css, output)
})
fs.echo(css, output)
}
const compileHtm = (entry, output) => {

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

View File

@ -305,6 +305,244 @@ const _Anot = (function() {
/*-----------------部分ES6的JS实现 start---------------*/
// ===============================
// ========== Promise ============
// ===============================
;(function(nativePromise) {
function _yes(val) {
return val
}
function _no(err) {
throw err
}
function done(callback) {
return this.then(callback, _no)
}
function fail(callback) {
return this.then(_yes, callback)
}
function defer() {
var obj = {}
obj.promise = new _Promise(function(yes, no) {
obj.resolve = yes
obj.reject = no
})
return obj
}
//成功的回调
function _resolve(obj, val) {
if (obj._state !== 'pending') {
return
}
if (val && typeof val.then === 'function') {
var method = val instanceof _Promise ? '_then' : 'then'
val[method](
function(v) {
_transmit(obj, v, true)
},
function(v) {
_transmit(obj, v, false)
}
)
} else {
_transmit(obj, val, true)
}
}
//失败的回调
function _reject(obj, val) {
if (obj._state !== 'pending') {
return
}
_transmit(obj, val, false)
}
// 改变Promise的_fired值并保持用户传参触发所有回调
function _transmit(obj, val, isResolved) {
obj._fired = true
obj._val = val
obj._state = isResolved ? 'fulfilled' : 'rejected'
fireCallback(obj, function() {
for (var i in obj.callback) {
obj._fire(obj.callback[i].yes, obj.callback[i].no)
}
})
}
function fireCallback(obj, callback) {
var isAsync = false
if (typeof obj.async === 'boolean') {
isAsync = obj.async
} else {
isAsync = obj.async = true
}
if (isAsync) {
setTimeout(callback, 0)
} else {
callback()
}
}
function _some(bool, iterable) {
iterable = Array.isArray(iterable) ? iterable : []
var n = 0
var res = []
var end = false
return new _Promise(function(yes, no) {
if (!iterable.length) no(res)
function loop(obj, idx) {
obj.then(
function(val) {
if (!end) {
res[idx] = val
n++
if (bool || n >= iterable.length) {
yes(bool ? val : res)
end = true
}
}
},
function(val) {
end = true
no(val)
}
)
}
for (var i = 0, len = iterable.length; i < len; i++) {
loop(iterable[i], i)
}
})
}
//---------------------------
var _Promise = function(callback) {
this.callback = []
var _this = this
if (typeof this !== 'object') {
throw new TypeError('Promises must be constructed via new')
}
if (typeof callback !== 'function') {
throw new TypeError('Argument must be a function')
}
callback(
function(val) {
_resolve(_this, val)
},
function(val) {
_reject(_this, val)
}
)
}
var self = {
_state: 1,
_fired: 1,
_val: 1,
callback: 1
}
_Promise.prototype = {
constructor: _Promise,
_state: 'pending',
_fired: false,
_fire: function(yes, no) {
if (this._state === 'rejected') {
if (typeof no === 'function') no(this._val)
else throw this._val
} else {
if (typeof yes === 'function') yes(this._val)
}
},
_then: function(yes, no) {
if (this._fired) {
var _this = this
fireCallback(_this, function() {
_this._fire(yes, no)
})
} else {
this.callback.push({ yes: yes, no: no })
}
},
then: function(yes, no) {
yes = typeof yes === 'function' ? yes : _yes
no = typeof no === 'function' ? no : _no
var _this = this
var next = new _Promise(function(resolve, reject) {
_this._then(
function(val) {
try {
val = yes(val)
} catch (err) {
return reject(err)
}
},
function(val) {
try {
val = no(val)
} catch (err) {
return reject(err)
}
resolve(val)
}
)
})
for (var i in _this) {
if (!self[i]) next[i] = _this[i]
}
return next
},
done: done,
catch: fail,
fail: fail
}
_Promise.all = function(arr) {
return _some(false, arr)
}
_Promise.race = function(arr) {
return _some(true, arr)
}
_Promise.defer = defer
_Promise.resolve = function(val) {
var obj = this.defer()
obj.resolve(val)
return obj.promise
}
_Promise.reject = function(val) {
var obj = this.defer()
obj.reject(val)
return obj.promise
}
if (/native code/.test(nativePromise)) {
nativePromise.prototype.done = done
nativePromise.prototype.fail = fail
if (!nativePromise.defer) {
nativePromise.defer = defer
}
}
window.Promise = nativePromise || _Promise
})(window.Promise)
if (!Object.assign) {
Object.defineProperty(Object, 'assign', {
enumerable: false,
@ -529,6 +767,33 @@ const _Anot = (function() {
/*-----------------部分ES6的JS实现 ending---------------*/
function cacheStore(tpye, key, val) {
if (!window[tpye]) {
return log('该浏览器不支持本地储存' + tpye)
}
if (this.type(key) === 'object') {
for (var i in key) {
window[tpye].setItem(i, key[i])
}
return
}
switch (arguments.length) {
case 2:
return window[tpye].getItem(key)
default:
if ((this.type(val) == 'string' && val.trim() === '') || val === null) {
window[tpye].removeItem(key)
return
}
if (this.type(val) !== 'object' && this.type(val) !== 'array') {
window[tpye].setItem(key, val.toString())
} else {
window[tpye].setItem(key, JSON.stringify(val))
}
}
}
Anot.mix({
rword: rword,
subscribers: subscribers,
@ -671,55 +936,32 @@ const _Anot = (function() {
},
/**
* [ls localStorage操作]
* @param {[type]} name [键名]
* @param {[type]} key [键名]
* @param {[type]} val [键值为空时删除]
* @return
*/
ls: function(name, val) {
if (!window.localStorage) {
return log('该浏览器不支持本地储存localStorage')
}
if (this.type(name) === 'object') {
for (var i in name) {
localStorage.setItem(i, name[i])
}
return
}
switch (arguments.length) {
case 1:
return localStorage.getItem(name)
default:
if (
(this.type(val) == 'string' && val.trim() === '') ||
val === null
) {
localStorage.removeItem(name)
return
}
if (this.type(val) !== 'object' && this.type(val) !== 'array') {
localStorage.setItem(name, val.toString())
} else {
localStorage.setItem(name, JSON.stringify(val))
}
}
ls: function(key, val) {
return cacheStore('localStorage', key, val)
},
ss: function(key, val) {
return cacheStore('sessionStorage', key, val)
},
/**
* [cookie cookie 操作 ]
* @param name [cookie名]
* @param value [cookie值]
* @param key [cookie名]
* @param val [cookie值]
* @param {[json]} opt [有效期域名路径等]
* @return {[boolean]} [读取时返回对应的值写入时返回true]
*/
cookie: function(name, value, opt) {
cookie: function(key, val, opt) {
if (arguments.length > 1) {
if (!name) {
if (!key) {
return
}
//设置默认的参数
opt = opt || {}
opt = this.mix(
opt = Object.assign(
{
expires: '',
path: '/',
@ -729,9 +971,9 @@ const _Anot = (function() {
opt
)
if (!value) {
if ((this.type(val) == 'string' && val.trim() === '') || val === null) {
document.cookie =
encodeURIComponent(name) +
encodeURIComponent(key) +
'=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=' +
opt.domain +
'; path=' +
@ -755,9 +997,9 @@ const _Anot = (function() {
}
}
document.cookie =
encodeURIComponent(name) +
encodeURIComponent(key) +
'=' +
encodeURIComponent(value) +
encodeURIComponent(val) +
opt.expires +
'; domain=' +
opt.domain +
@ -767,24 +1009,15 @@ const _Anot = (function() {
opt.secure
return true
} else {
if (!name) {
var keys = document.cookie
.replace(
/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g,
''
)
.split(/\s*(?:\=[^;]*)?;\s*/)
for (var i = 0, len = keys.length; i < len; i++) {
keys[i] = decodeURIComponent(keys[i])
}
return keys
if (!key) {
return document.cookie
}
return (
decodeURIComponent(
document.cookie.replace(
new RegExp(
'(?:(?:^|.*;)\\s*' +
encodeURIComponent(name).replace(/[\-\.\+\*]/g, '\\$&') +
encodeURIComponent(key).replace(/[\-\.\+\*]/g, '\\$&') +
'\\s*\\=\\s*([^;]*).*$)|^.*$'
),
'$1'
@ -1527,7 +1760,7 @@ const _Anot = (function() {
$vmodel.$active = true
$vmodel.mounted = mounted
if (old && old.$up) {
if (old && old.$up && old.$up.$children) {
old.$up.$children.push($vmodel)
}
@ -3467,6 +3700,19 @@ const _Anot = (function() {
}
}
function parseSlot(collections) {
var arr = aslice.call(collections, 0)
var obj = {}
arr.forEach(function(elem) {
var slot = elem.getAttribute('slot')
if (slot) {
elem.removeAttribute('slot')
obj[slot] = elem.outerHTML
}
})
return obj
}
Anot.components = {}
Anot.component = function(name, opts) {
if (opts) {
@ -3531,16 +3777,20 @@ const _Anot = (function() {
componentWillMount.call(vmodel)
globalHooks.componentWillMount.call(null, vmodel)
if (!elem.content.firstElementChild) {
var slots = null
if (elem.content.firstElementChild) {
slots = parseSlot(elem.content.children)
}
Anot.clearHTML(elem)
var html = render.call(vmodel) || ''
var html = render.call(vmodel, slots) || ''
html = html.replace(/<\w+[^>]*>/g, function(m, s) {
return m.replace(/[\n\t\s]{1,}/g, ' ')
})
elem.innerHTML = html
}
// 组件所使用的标签是temlate,所以必须要要用子元素替换掉
var child = elem.content.firstElementChild

View File

@ -320,6 +320,244 @@
/*-----------------部分ES6的JS实现 start---------------*/
// ===============================
// ========== Promise ============
// ===============================
;(function(nativePromise) {
function _yes(val) {
return val
}
function _no(err) {
throw err
}
function done(callback) {
return this.then(callback, _no)
}
function fail(callback) {
return this.then(_yes, callback)
}
function defer() {
var obj = {}
obj.promise = new _Promise(function(yes, no) {
obj.resolve = yes
obj.reject = no
})
return obj
}
//成功的回调
function _resolve(obj, val) {
if (obj._state !== 'pending') {
return
}
if (val && typeof val.then === 'function') {
var method = val instanceof _Promise ? '_then' : 'then'
val[method](
function(v) {
_transmit(obj, v, true)
},
function(v) {
_transmit(obj, v, false)
}
)
} else {
_transmit(obj, val, true)
}
}
//失败的回调
function _reject(obj, val) {
if (obj._state !== 'pending') {
return
}
_transmit(obj, val, false)
}
// 改变Promise的_fired值并保持用户传参触发所有回调
function _transmit(obj, val, isResolved) {
obj._fired = true
obj._val = val
obj._state = isResolved ? 'fulfilled' : 'rejected'
fireCallback(obj, function() {
for (var i in obj.callback) {
obj._fire(obj.callback[i].yes, obj.callback[i].no)
}
})
}
function fireCallback(obj, callback) {
var isAsync = false
if (typeof obj.async === 'boolean') {
isAsync = obj.async
} else {
isAsync = obj.async = true
}
if (isAsync) {
setTimeout(callback, 0)
} else {
callback()
}
}
function _some(bool, iterable) {
iterable = Array.isArray(iterable) ? iterable : []
var n = 0
var res = []
var end = false
return new _Promise(function(yes, no) {
if (!iterable.length) no(res)
function loop(obj, idx) {
obj.then(
function(val) {
if (!end) {
res[idx] = val
n++
if (bool || n >= iterable.length) {
yes(bool ? val : res)
end = true
}
}
},
function(val) {
end = true
no(val)
}
)
}
for (var i = 0, len = iterable.length; i < len; i++) {
loop(iterable[i], i)
}
})
}
//---------------------------
var _Promise = function(callback) {
this.callback = []
var _this = this
if (typeof this !== 'object') {
throw new TypeError('Promises must be constructed via new')
}
if (typeof callback !== 'function') {
throw new TypeError('Argument must be a function')
}
callback(
function(val) {
_resolve(_this, val)
},
function(val) {
_reject(_this, val)
}
)
}
var self = {
_state: 1,
_fired: 1,
_val: 1,
callback: 1
}
_Promise.prototype = {
constructor: _Promise,
_state: 'pending',
_fired: false,
_fire: function(yes, no) {
if (this._state === 'rejected') {
if (typeof no === 'function') no(this._val)
else throw this._val
} else {
if (typeof yes === 'function') yes(this._val)
}
},
_then: function(yes, no) {
if (this._fired) {
var _this = this
fireCallback(_this, function() {
_this._fire(yes, no)
})
} else {
this.callback.push({ yes: yes, no: no })
}
},
then: function(yes, no) {
yes = typeof yes === 'function' ? yes : _yes
no = typeof no === 'function' ? no : _no
var _this = this
var next = new _Promise(function(resolve, reject) {
_this._then(
function(val) {
try {
val = yes(val)
} catch (err) {
return reject(err)
}
},
function(val) {
try {
val = no(val)
} catch (err) {
return reject(err)
}
resolve(val)
}
)
})
for (var i in _this) {
if (!self[i]) next[i] = _this[i]
}
return next
},
done: done,
catch: fail,
fail: fail
}
_Promise.all = function(arr) {
return _some(false, arr)
}
_Promise.race = function(arr) {
return _some(true, arr)
}
_Promise.defer = defer
_Promise.resolve = function(val) {
var obj = this.defer()
obj.resolve(val)
return obj.promise
}
_Promise.reject = function(val) {
var obj = this.defer()
obj.reject(val)
return obj.promise
}
if (/native code/.test(nativePromise)) {
nativePromise.prototype.done = done
nativePromise.prototype.fail = fail
if (!nativePromise.defer) {
nativePromise.defer = defer
}
}
window.Promise = nativePromise || _Promise
})(window.Promise)
if (!Object.assign) {
Object.defineProperty(Object, 'assign', {
enumerable: false,
@ -544,6 +782,33 @@
/*-----------------部分ES6的JS实现 ending---------------*/
function cacheStore(tpye, key, val) {
if (!window[tpye]) {
return log('该浏览器不支持本地储存' + tpye)
}
if (this.type(key) === 'object') {
for (var i in key) {
window[tpye].setItem(i, key[i])
}
return
}
switch (arguments.length) {
case 2:
return window[tpye].getItem(key)
default:
if ((this.type(val) == 'string' && val.trim() === '') || val === null) {
window[tpye].removeItem(key)
return
}
if (this.type(val) !== 'object' && this.type(val) !== 'array') {
window[tpye].setItem(key, val.toString())
} else {
window[tpye].setItem(key, JSON.stringify(val))
}
}
}
Anot.mix({
rword: rword,
subscribers: subscribers,
@ -686,55 +951,32 @@
},
/**
* [ls localStorage操作]
* @param {[type]} name [键名]
* @param {[type]} key [键名]
* @param {[type]} val [键值为空时删除]
* @return
*/
ls: function(name, val) {
if (!window.localStorage) {
return log('该浏览器不支持本地储存localStorage')
}
if (this.type(name) === 'object') {
for (var i in name) {
localStorage.setItem(i, name[i])
}
return
}
switch (arguments.length) {
case 1:
return localStorage.getItem(name)
default:
if (
(this.type(val) == 'string' && val.trim() === '') ||
val === null
) {
localStorage.removeItem(name)
return
}
if (this.type(val) !== 'object' && this.type(val) !== 'array') {
localStorage.setItem(name, val.toString())
} else {
localStorage.setItem(name, JSON.stringify(val))
}
}
ls: function(key, val) {
return cacheStore('localStorage', key, val)
},
ss: function(key, val) {
return cacheStore('sessionStorage', key, val)
},
/**
* [cookie cookie 操作 ]
* @param name [cookie名]
* @param value [cookie值]
* @param key [cookie名]
* @param val [cookie值]
* @param {[json]} opt [有效期域名路径等]
* @return {[boolean]} [读取时返回对应的值写入时返回true]
*/
cookie: function(name, value, opt) {
cookie: function(key, val, opt) {
if (arguments.length > 1) {
if (!name) {
if (!key) {
return
}
//设置默认的参数
opt = opt || {}
opt = this.mix(
opt = Object.assign(
{
expires: '',
path: '/',
@ -744,9 +986,9 @@
opt
)
if (!value) {
if ((this.type(val) == 'string' && val.trim() === '') || val === null) {
document.cookie =
encodeURIComponent(name) +
encodeURIComponent(key) +
'=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=' +
opt.domain +
'; path=' +
@ -770,9 +1012,9 @@
}
}
document.cookie =
encodeURIComponent(name) +
encodeURIComponent(key) +
'=' +
encodeURIComponent(value) +
encodeURIComponent(val) +
opt.expires +
'; domain=' +
opt.domain +
@ -782,24 +1024,15 @@
opt.secure
return true
} else {
if (!name) {
var keys = document.cookie
.replace(
/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g,
''
)
.split(/\s*(?:\=[^;]*)?;\s*/)
for (var i = 0, len = keys.length; i < len; i++) {
keys[i] = decodeURIComponent(keys[i])
}
return keys
if (!key) {
return document.cookie
}
return (
decodeURIComponent(
document.cookie.replace(
new RegExp(
'(?:(?:^|.*;)\\s*' +
encodeURIComponent(name).replace(/[\-\.\+\*]/g, '\\$&') +
encodeURIComponent(key).replace(/[\-\.\+\*]/g, '\\$&') +
'\\s*\\=\\s*([^;]*).*$)|^.*$'
),
'$1'
@ -1542,7 +1775,7 @@
$vmodel.$active = true
$vmodel.mounted = mounted
if (old && old.$up) {
if (old && old.$up && old.$up.$children) {
old.$up.$children.push($vmodel)
}
@ -3482,6 +3715,19 @@
}
}
function parseSlot(collections) {
var arr = aslice.call(collections, 0)
var obj = {}
arr.forEach(function(elem) {
var slot = elem.getAttribute('slot')
if (slot) {
elem.removeAttribute('slot')
obj[slot] = elem.outerHTML
}
})
return obj
}
Anot.components = {}
Anot.component = function(name, opts) {
if (opts) {
@ -3546,16 +3792,20 @@
componentWillMount.call(vmodel)
globalHooks.componentWillMount.call(null, vmodel)
if (!elem.content.firstElementChild) {
var slots = null
if (elem.content.firstElementChild) {
slots = parseSlot(elem.content.children)
}
Anot.clearHTML(elem)
var html = render.call(vmodel) || ''
var html = render.call(vmodel, slots) || ''
html = html.replace(/<\w+[^>]*>/g, function(m, s) {
return m.replace(/[\n\t\s]{1,}/g, ' ')
})
elem.innerHTML = html
}
// 组件所使用的标签是temlate,所以必须要要用子元素替换掉
var child = elem.content.firstElementChild
@ -5811,7 +6061,9 @@
}
oDate = new Date(stamp)
if (oDate + '' === 'Invalid Date') return 'Invalid Date'
if (oDate + '' === 'Invalid Date') {
return 'Invalid Date'
}
} else {
oDate = stamp
}
@ -5867,9 +6119,7 @@
var ext = '.js' //默认拓展名
var res = 'js' // 默认资源类型
var suffix = ['.js', '.css']
var cssfix = /\.(scss|sass|less)$/
name = name.replace(/\.[a-z0-9]+$/g, function(match) {
match = match.replace(cssfix, '.css')
ext = match
res = suffix.indexOf(match) > -1 ? match.slice(1) : 'text'
return ''

View File

@ -51,22 +51,22 @@ function update(currPage, vm) {
}
const tmpls = {
home: `<button class="do-ui-font button home"
home: `<button class="do-icon-dbl-left button"
:css="{'border-radius': props.radius}"
:attr-disabled="currPage === 1"
:data="{to: parseUrl(1)}"
:click="setPage(1, $event)"></button>`,
end: `<button class="do-ui-font button end"
end: `<button class="do-icon-dbl-right button"
:css="{'border-radius': props.radius}"
:attr-disabled="currPage === totalPage"
:data="{to: parseUrl(totalPage)}"
:click="setPage(totalPage, $event)"></button>`,
prev: `<button class="do-ui-font button prev"
prev: `<button class="do-icon-left button"
:css="{'border-radius': props.radius}"
:attr-disabled="{disabled: currPage < 2}"
:data="{to: parseUrl(currPage - 1)}"
:click="setPage(currPage - 1, $event)"></button>`,
next: `<button class="do-ui-font button next"
next: `<button class="do-icon-right button"
:css="{'border-radius': props.radius}"
:attr-disabled="{disabled: currPage >= totalPage}"
:data="{to: parseUrl(currPage + 1)}"
@ -83,7 +83,8 @@ const tmpls = {
total: `<span class="total-box">共 {{totalPage}} 页 {{totalItems}} 条</span>`,
jumper: `<div class="input-box">前往
<input type="text" :duplex="inputPage" :keyup="setPage(null, $event)">
</div>`
</div>`,
slot: `<slot name="extra" />`
}
export default Anot.component('pager', {
@ -119,7 +120,7 @@ export default Anot.component('pager', {
delete props.color
delete props.size
},
render: function() {
render: function(slots) {
let { layout, theme, simpleMode } = this.props
if (simpleMode) {
layout = ['prev', 'curr', 'next']
@ -130,7 +131,15 @@ export default Anot.component('pager', {
}
layout = layout.split(',')
}
layout = layout.map(it => tmpls[it] || '')
layout = layout.map(it => {
if (it === 'slot') {
if (slots && slots.extra) {
return slots.extra
}
} else {
return tmpls[it] || ''
}
})
return `
<div
class="do-pager do-fn-noselect"

View File

@ -20,16 +20,8 @@
.button,.page {min-width:40px;height:40px}
}
.button,.page {display:inline-block;border:0;color: nth($cgr, 1);text-decoration:none;cursor:pointer;vertical-align:top;font-size:14px;font-weight:100;
&.home::after {content:"\e691";font-size:18px;}
&.prev::after {content:"\e67c";font-size:18px;}
&.next::after {content:"\e66e";font-size:18px;}
&.end::after {content:"\e693";font-size:18px;}
}
.button,.page {display:inline-block;border:0;color: nth($cgr, 1);text-decoration:none;cursor:pointer;vertical-align:top;font-size:14px;font-weight:100;}
.button {font-size:18px;}
.curr, .disabled {cursor:default;}
&.skin-1 {width:100%;

View File

@ -1,231 +0,0 @@
/**
*
* @authors yutent (yutent@doui.cc)
* @date 2016-11-26 16:35:45
*
*/
var _Promise = function(callback) {
this.callback = []
var _this = this
if (typeof this !== 'object')
throw new TypeError('Promises must be constructed via new')
if (typeof callback !== 'function')
throw new TypeError('Argument must be a function')
callback(
function(val) {
_resolve(_this, val)
},
function(val) {
_reject(_this, val)
}
)
}
var self = {
_state: 1,
_fired: 1,
_val: 1,
callback: 1
}
_Promise.prototype = {
constructor: _Promise,
_state: 'pending',
_fired: false,
_fire: function(yes, no) {
if (this._state === 'rejected') {
if (typeof no === 'function') no(this._val)
else throw this._val
} else {
if (typeof yes === 'function') yes(this._val)
}
},
_then: function(yes, no) {
if (this._fired) {
var _this = this
fireCallback(_this, function() {
_this._fire(yes, no)
})
} else {
this.callback.push({ yes: yes, no: no })
}
},
then: function(yes, no) {
yes = typeof yes === 'function' ? yes : _yes
no = typeof no === 'function' ? no : _no
var _this = this
var next = new _Promise(function(resolve, reject) {
_this._then(
function(val) {
try {
val = yes(val)
} catch (err) {
return reject(err)
}
},
function(val) {
try {
val = no(val)
} catch (err) {
return reject(err)
}
resolve(val)
}
)
})
for (var i in _this) {
if (!self[i]) next[i] = _this[i]
}
return next
},
done: done,
catch: fail,
fail: fail
}
_Promise.all = function(arr) {
return _some(false, arr)
}
_Promise.race = function(arr) {
return _some(true, arr)
}
_Promise.defer = defer
_Promise.resolve = function(val) {
var obj = this.defer()
obj.resolve(val)
return obj.promise
}
_Promise.reject = function(val) {
var obj = this.defer()
obj.reject(val)
return obj.promise
}
// -----------------------------------------------------------
function _yes(val) {
return val
}
function _no(err) {
throw err
}
function done(callback) {
return this.then(callback, _no)
}
function fail(callback) {
return this.then(_yes, callback)
}
function defer() {
var obj = {}
obj.promise = new this(function(yes, no) {
obj.resolve = yes
obj.reject = no
})
return obj
}
//成功的回调
function _resolve(obj, val) {
if (obj._state !== 'pending') return
if (val && typeof val.then === 'function') {
var method = val instanceof _Promise ? '_then' : 'then'
val[method](
function(v) {
_transmit(obj, v, true)
},
function(v) {
_transmit(obj, v, false)
}
)
} else {
_transmit(obj, val, true)
}
}
//失败的回调
function _reject(obj, val) {
if (obj._state !== 'pending') return
_transmit(obj, val, false)
}
// 改变Promise的_fired值并保持用户传参触发所有回调
function _transmit(obj, val, isResolved) {
obj._fired = true
obj._val = val
obj._state = isResolved ? 'fulfilled' : 'rejected'
fireCallback(obj, function() {
for (var i in obj.callback) {
obj._fire(obj.callback[i].yes, obj.callback[i].no)
}
})
}
function fireCallback(obj, callback) {
var isAsync = false
if (typeof obj.async === 'boolean') isAsync = obj.async
else isAsync = obj.async = true
if (isAsync) setTimeout(callback, 0)
else callback()
}
function _some(bool, iterable) {
iterable = Array.isArray(iterable) ? iterable : []
var n = 0
var res = []
var end = false
return new _Promise(function(yes, no) {
if (!iterable.length) no(res)
function loop(obj, idx) {
obj.then(
function(val) {
if (!end) {
res[idx] = val
n++
if (bool || n >= iterable.length) {
yes(bool ? val : res)
end = true
}
}
},
function(val) {
end = true
no(val)
}
)
}
for (var i = 0, len = iterable.length; i < len; i++) {
loop(iterable[i], i)
}
})
}
// ---------------------------------------------------------------
var nativePromise = window.Promise
if (/native code/.test(nativePromise)) {
nativePromise.prototype.done = done
nativePromise.prototype.fail = fail
if (!nativePromise.defer) nativePromise.defer = defer
}
export default (window.Promise = nativePromise || _Promise)

View File

@ -6,7 +6,6 @@
*/
'use strict'
import 'promise/index'
import Format from './lib/format'
// 本地协议/头 判断正则
@ -173,8 +172,7 @@ class _Request {
//成功的回调
let isSucc = isTimeout
? false
: (this.transport.status >= 200 && this.transport.status < 300) ||
this.transport.status === 304
: this.transport.status >= 200 && this.transport.status < 400
let headers =
(!isTimeout && this.transport.getAllResponseHeaders().split('\n')) || []
@ -225,7 +223,11 @@ class _Request {
result.statusText = error[10012]
}
if (result.status >= 200 && result.status < 400) {
this.defer.resolve(result)
} else {
this.defer.reject(result)
}
}
delete this.transport
delete this.opt

View File

@ -1,174 +0,0 @@
if ('object' != typeof JSON) {
JSON = {}
}
export default (function() {
'use strict'
function f(t) {
return 10 > t ? '0' + t : t
}
function this_value() {
return this.valueOf()
}
function quote(t) {
return (
(rx_escapable.lastIndex = 0),
rx_escapable.test(t)
? '"' +
t.replace(rx_escapable, function(t) {
var e = meta[t]
return 'string' == typeof e
? e
: '\\u' + ('0000' + t.charCodeAt(0).toString(16)).slice(-4)
}) +
'"'
: '"' + t + '"'
)
}
function str(t, e) {
var r,
n,
o,
u,
f,
a = gap,
i = e[t]
switch ((i &&
'object' == typeof i &&
'function' == typeof i.toJSON &&
(i = i.toJSON(t)),
'function' == typeof rep && (i = rep.call(e, t, i)),
typeof i)) {
case 'string':
return quote(i)
case 'number':
return isFinite(i) ? String(i) : 'null'
case 'boolean':
case 'null':
return String(i)
case 'object':
if (!i) return 'null'
if (
((gap += indent),
(f = []),
'[object Array]' === Object.prototype.toString.apply(i))
) {
for (u = i.length, r = 0; u > r; r += 1) f[r] = str(r, i) || 'null'
return (
(o =
0 === f.length
? '[]'
: gap
? '[\n' + gap + f.join(',\n' + gap) + '\n' + a + ']'
: '[' + f.join(',') + ']'),
(gap = a),
o
)
}
if (rep && 'object' == typeof rep)
for (u = rep.length, r = 0; u > r; r += 1)
'string' == typeof rep[r] &&
((n = rep[r]),
(o = str(n, i)),
o && f.push(quote(n) + (gap ? ': ' : ':') + o))
else
for (n in i)
Object.prototype.hasOwnProperty.call(i, n) &&
((o = str(n, i)), o && f.push(quote(n) + (gap ? ': ' : ':') + o))
return (
(o =
0 === f.length
? '{}'
: gap
? '{\n' + gap + f.join(',\n' + gap) + '\n' + a + '}'
: '{' + f.join(',') + '}'),
(gap = a),
o
)
}
}
var rx_one = /^[\],:{}\s]*$/,
rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rx_four = /(?:^|:|,)(?:\s*\[)+/g,
rx_escapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g
'function' != typeof Date.prototype.toJSON &&
((Date.prototype.toJSON = function() {
return isFinite(this.valueOf())
? this.getUTCFullYear() +
'-' +
f(this.getUTCMonth() + 1) +
'-' +
f(this.getUTCDate()) +
'T' +
f(this.getUTCHours()) +
':' +
f(this.getUTCMinutes()) +
':' +
f(this.getUTCSeconds()) +
'Z'
: null
}),
(Boolean.prototype.toJSON = this_value),
(Number.prototype.toJSON = this_value),
(String.prototype.toJSON = this_value))
var gap, indent, meta, rep
'function' != typeof JSON.stringify &&
((meta = {
'\b': '\\b',
' ': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"': '\\"',
'\\': '\\\\'
}),
(JSON.stringify = function(t, e, r) {
var n
if (((gap = ''), (indent = ''), 'number' == typeof r))
for (n = 0; r > n; n += 1) indent += ' '
else 'string' == typeof r && (indent = r)
if (
((rep = e),
e &&
'function' != typeof e &&
('object' != typeof e || 'number' != typeof e.length))
)
throw new Error('JSON.stringify')
return str('', { '': t })
})),
'function' != typeof JSON.parse &&
(JSON.parse = function(text, reviver) {
function walk(t, e) {
var r,
n,
o = t[e]
if (o && 'object' == typeof o)
for (r in o)
Object.prototype.hasOwnProperty.call(o, r) &&
((n = walk(o, r)), void 0 !== n ? (o[r] = n) : delete o[r])
return reviver.call(t, e, o)
}
var j
if (
((text = String(text)),
(rx_dangerous.lastIndex = 0),
rx_dangerous.test(text) &&
(text = text.replace(rx_dangerous, function(t) {
return '\\u' + ('0000' + t.charCodeAt(0).toString(16)).slice(-4)
})),
rx_one.test(
text
.replace(rx_two, '@')
.replace(rx_three, ']')
.replace(rx_four, '')
))
)
return (
(j = eval('(' + text + ')')),
'function' == typeof reviver ? walk({ '': j }, '') : j
)
throw new SyntaxError('JSON.parse')
})
return JSON
})()