Fixed m.request initialValue tests

This commit is contained in:
Barney 2014-11-10 15:32:31 +00:00
parent 71a6321c46
commit b5de0c2b4d
3 changed files with 143 additions and 75 deletions

View file

@ -1,10 +1,6 @@
Mithril = m = new function app(window, undefined) { Mithril = m = new function app(window, undefined) {
var sObj = "[object Object]", sArr = "[object Array]", sStr = "[object String]" var sObj = "[object Object]", sArr = "[object Array]", sStr = "[object String]", sFn = "function"
function type(obj) {return {}.toString.call(obj)} var type = {}.toString
function isObj(obj) {return obj != null && type(obj) == sObj}
function isArr(obj) {return type(obj) == sArr}
function isFn(obj) {return typeof obj == "function"}
function isStr(obj){ return type(obj) == sStr}
var parser = /(?:(^|#|\.)([^#\.\[\]]+))|(\[.+?\])/g, attrParser = /\[(.+?)(?:=("|'|)(.*?)\2)?\]/ var parser = /(?:(^|#|\.)([^#\.\[\]]+))|(\[.+?\])/g, attrParser = /\[(.+?)(?:=("|'|)(.*?)\2)?\]/
var voidElements = /AREA|BASE|BR|COL|COMMAND|EMBED|HR|IMG|INPUT|KEYGEN|LINK|META|PARAM|SOURCE|TRACK|WBR/ var voidElements = /AREA|BASE|BR|COL|COMMAND|EMBED|HR|IMG|INPUT|KEYGEN|LINK|META|PARAM|SOURCE|TRACK|WBR/
@ -23,7 +19,7 @@ Mithril = m = new function app(window, undefined) {
*/ */
function m() { function m() {
var args = [].slice.call(arguments) var args = [].slice.call(arguments)
var hasAttrs = isObj(args[1]) && !("tag" in args[1]) && !("subtree" in args[1]) var hasAttrs = args[1] != null && type.call(args[1]) == sObj && !("tag" in args[1]) && !("subtree" in args[1])
var attrs = hasAttrs ? args[1] : {} var attrs = hasAttrs ? args[1] : {}
var classAttrName = "class" in attrs ? "class" : "className" var classAttrName = "class" in attrs ? "class" : "className"
var cell = {tag: "div", attrs: {}} var cell = {tag: "div", attrs: {}}
@ -41,7 +37,7 @@ Mithril = m = new function app(window, undefined) {
var children = hasAttrs ? args[2] : args[1] var children = hasAttrs ? args[2] : args[1]
if (isArr(children)) { if (type.call(children) == sArr) {
cell.children = children cell.children = children
} }
else { else {
@ -82,7 +78,7 @@ Mithril = m = new function app(window, undefined) {
//- it simplifies diffing code //- it simplifies diffing code
if (data == null) data = "" if (data == null) data = ""
if (data.subtree === "retain") return cached if (data.subtree === "retain") return cached
var cachedType = type(cached), dataType = type(data) var cachedType = type.call(cached), dataType = type.call(data)
if (cached == null || cachedType != dataType) { if (cached == null || cachedType != dataType) {
if (cached != null) { if (cached != null) {
if (parentCache && parentCache.nodes) { if (parentCache && parentCache.nodes) {
@ -170,7 +166,13 @@ Mithril = m = new function app(window, undefined) {
var item = build(parentElement, parentTag, cached, index, data[i], cached[cacheCount], shouldReattach, index + subArrayCount || subArrayCount, editable, namespace, configs) var item = build(parentElement, parentTag, cached, index, data[i], cached[cacheCount], shouldReattach, index + subArrayCount || subArrayCount, editable, namespace, configs)
if (item === undefined) continue if (item === undefined) continue
if (!item.nodes.intact) intact = false if (!item.nodes.intact) intact = false
subArrayCount += isArr(item) ? item.length : 1 if (item.$trusted) {
//fix offset of next element if item was a trusted string w/ more than one html element
//the first clause in the regexp matches elements
//the second clause (after the pipe) matches text nodes
subArrayCount += (item.match(/<[^\/]|\>\s*[^<]/g) || []).length
}
else subArrayCount += type.call(item) == sArr ? item.length : 1
cached[cacheCount++] = item cached[cacheCount++] = item
} }
if (!intact) { if (!intact) {
@ -194,12 +196,16 @@ Mithril = m = new function app(window, undefined) {
} }
} }
else if (data != null && dataType == sObj) { else if (data != null && dataType == sObj) {
if (!data.attrs) data.attrs = {}
if (!cached.attrs) cached.attrs = {}
var dataAttrKeys = Object.keys(data.attrs)
//if an element is different enough from the one in cache, recreate it //if an element is different enough from the one in cache, recreate it
if (data.tag != cached.tag || Object.keys(data.attrs).join() != Object.keys(cached.attrs).join() || data.attrs.id != cached.attrs.id) { if (data.tag != cached.tag || dataAttrKeys.join() != Object.keys(cached.attrs).join() || data.attrs.id != cached.attrs.id) {
clear(cached.nodes) if (cached.nodes.length) clear(cached.nodes)
if (cached.configContext && isFn(cached.configContext.onunload)) cached.configContext.onunload() if (cached.configContext && typeof cached.configContext.onunload == sFn) cached.configContext.onunload()
} }
if (!isStr(data.tag)) return if (type.call(data.tag) != sStr) return
var node, isNew = cached.nodes.length === 0 var node, isNew = cached.nodes.length === 0
if (data.attrs.xmlns) namespace = data.attrs.xmlns if (data.attrs.xmlns) namespace = data.attrs.xmlns
@ -210,23 +216,26 @@ Mithril = m = new function app(window, undefined) {
cached = { cached = {
tag: data.tag, tag: data.tag,
//set attributes first, then create children //set attributes first, then create children
attrs: setAttributes(node, data.tag, data.attrs, {}, namespace), attrs: dataAttrKeys.length ? setAttributes(node, data.tag, data.attrs, {}, namespace) : {},
children: build(node, data.tag, undefined, undefined, data.children, cached.children, true, 0, data.attrs.contenteditable ? node : editable, namespace, configs), children: data.children != null && data.children.length > 0 ?
build(node, data.tag, undefined, undefined, data.children, cached.children, true, 0, data.attrs.contenteditable ? node : editable, namespace, configs) :
data.children,
nodes: [node] nodes: [node]
} }
if (cached.children && !cached.children.nodes) cached.children.nodes = []
//edge case: setting value on <select> doesn't work before children exist, so set it again after children have been created //edge case: setting value on <select> doesn't work before children exist, so set it again after children have been created
if (data.tag == "select" && data.attrs.value) setAttributes(node, data.tag, {value: data.attrs.value}, {}, namespace) if (data.tag == "select" && data.attrs.value) setAttributes(node, data.tag, {value: data.attrs.value}, {}, namespace)
parentElement.insertBefore(node, parentElement.childNodes[index] || null) parentElement.insertBefore(node, parentElement.childNodes[index] || null)
} }
else { else {
node = cached.nodes[0] node = cached.nodes[0]
setAttributes(node, data.tag, data.attrs, cached.attrs, namespace) if (dataAttrKeys.length) setAttributes(node, data.tag, data.attrs, cached.attrs, namespace)
cached.children = build(node, data.tag, undefined, undefined, data.children, cached.children, false, 0, data.attrs.contenteditable ? node : editable, namespace, configs) cached.children = build(node, data.tag, undefined, undefined, data.children, cached.children, false, 0, data.attrs.contenteditable ? node : editable, namespace, configs)
cached.nodes.intact = true cached.nodes.intact = true
if (shouldReattach === true && node != null) parentElement.insertBefore(node, parentElement.childNodes[index] || null) if (shouldReattach === true && node != null) parentElement.insertBefore(node, parentElement.childNodes[index] || null)
} }
//schedule configs to be called. They are called after `build` finishes running //schedule configs to be called. They are called after `build` finishes running
if (isFn(data.attrs["config"])) { if (typeof data.attrs["config"] == sFn) {
var context = cached.configContext = cached.configContext || {} var context = cached.configContext = cached.configContext || {}
// bind // bind
@ -238,7 +247,7 @@ Mithril = m = new function app(window, undefined) {
configs.push(callback(data, [node, !isNew, context, cached])) configs.push(callback(data, [node, !isNew, context, cached]))
} }
} }
else if (!isFn(dataType)) { else if (typeof dataType != sFn) {
//handle text nodes //handle text nodes
var nodes var nodes
if (cached.nodes.length === 0) { if (cached.nodes.length === 0) {
@ -293,11 +302,11 @@ Mithril = m = new function app(window, undefined) {
//we don't ignore `key` because it must be unique and having it on the DOM helps debugging //we don't ignore `key` because it must be unique and having it on the DOM helps debugging
if (attrName === "config") continue if (attrName === "config") continue
//hook event handlers to the auto-redrawing system //hook event handlers to the auto-redrawing system
else if (isFn(dataAttr) && attrName.indexOf("on") == 0) { else if (typeof dataAttr == sFn && attrName.indexOf("on") == 0) {
node[attrName] = autoredraw(dataAttr, node) node[attrName] = autoredraw(dataAttr, node)
} }
//handle `style: {...}` //handle `style: {...}`
else if (attrName === "style" && isObj(dataAttr)) { else if (attrName === "style" && dataAttr != null && type.call(dataAttr) == sObj) {
for (var rule in dataAttr) { for (var rule in dataAttr) {
if (cachedAttr == null || cachedAttr[rule] !== dataAttr[rule]) node.style[rule] = dataAttr[rule] if (cachedAttr == null || cachedAttr[rule] !== dataAttr[rule]) node.style[rule] = dataAttr[rule]
} }
@ -338,9 +347,9 @@ Mithril = m = new function app(window, undefined) {
if (nodes.length != 0) nodes.length = 0 if (nodes.length != 0) nodes.length = 0
} }
function unload(cached) { function unload(cached) {
if (cached.configContext && isFn(cached.configContext.onunload)) cached.configContext.onunload() if (cached.configContext && typeof cached.configContext.onunload == sFn) cached.configContext.onunload()
if (cached.children) { if (cached.children) {
if (isArr(cached.children)) { if (type.call(cached.children) == sArr) {
for (var i = 0; i < cached.children.length; i++) unload(cached.children[i]) for (var i = 0; i < cached.children.length; i++) unload(cached.children[i])
} }
else if (cached.children.tag) unload(cached.children) else if (cached.children.tag) unload(cached.children)
@ -367,13 +376,19 @@ Mithril = m = new function app(window, undefined) {
return nodes return nodes
} }
function flatten(data) { function flatten(data) {
var flattened = [] var index = 0
for (var i = 0; i < data.length; i++) { loop: while (true) {
var item = data[i] for (var i = index; i < data.length; i++) {
if (isArr(item)) flattened.push.apply(flattened, flatten(item)) var item = data[i]
else flattened.push(item) if (type.call(data[i]) == sArr) {
index = i
data = data.concat.apply([], data)
continue loop
}
}
break
} }
return flattened return data
} }
function autoredraw(callback, object) { function autoredraw(callback, object) {
return function(e) { return function(e) {
@ -436,33 +451,25 @@ Mithril = m = new function app(window, undefined) {
return store return store
} }
prop.toString = function(){
return store.toString();
}
prop.valueOf = function(){
return store.valueOf();
}
return prop return prop
} }
m.prop = function (store) { m.prop = function (store) {
//note: using non-strict equality check here because we're checking if store is null OR undefined //note: using non-strict equality check here because we're checking if store is null OR undefined
if ((isObj(store) || isFn(store)) && store != null && isFn(store.then)) { if (((store != null && type.call(store) == sObj) || typeof store == sFn) && typeof store.then == sFn) {
return propify(store) return propify(store)
} }
return gettersetter(store) return gettersetter(store)
} }
var roots = [], modules = [], controllers = [], lastRedrawId = null, lastRedrawCallTime = 0, computePostRedrawHook = null, prevented = false var roots = [], modules = [], controllers = [], lastRedrawId = null, lastRedrawCallTime = 0, computePostRedrawHook = null, prevented = false, topModule
var FRAME_BUDGET = 16 //60 frames per second = 1 call per 16 ms var FRAME_BUDGET = 16 //60 frames per second = 1 call per 16 ms
m.module = function(root, module) { m.module = function(root, module) {
var index = roots.indexOf(root) var index = roots.indexOf(root)
if (index < 0) index = roots.length if (index < 0) index = roots.length
var isPrevented = false var isPrevented = false
if (controllers[index] && isFn(controllers[index].onunload)) { if (controllers[index] && typeof controllers[index].onunload == sFn) {
var event = { var event = {
preventDefault: function() {isPrevented = true} preventDefault: function() {isPrevented = true}
} }
@ -472,8 +479,14 @@ Mithril = m = new function app(window, undefined) {
m.redraw.strategy("all") m.redraw.strategy("all")
m.startComputation() m.startComputation()
roots[index] = root roots[index] = root
modules[index] = module var currentModule = topModule = module
controllers[index] = new module.controller var controller = new module.controller
//controllers may call m.module recursively (via m.route redirects, for example)
//this conditional ensures only the last recursive m.module call is applied
if (currentModule == topModule) {
controllers[index] = controller
modules[index] = module
}
m.endComputation() m.endComputation()
return controllers[index] return controllers[index]
} }
@ -500,7 +513,9 @@ Mithril = m = new function app(window, undefined) {
function redraw() { function redraw() {
var mode = m.redraw.strategy() var mode = m.redraw.strategy()
for (var i = 0; i < roots.length; i++) { for (var i = 0; i < roots.length; i++) {
if (controllers[i] && mode != "none") m.render(roots[i], modules[i].view(controllers[i]), mode == "all") if (controllers[i] && mode != "none") {
m.render(roots[i], modules[i].view(controllers[i]), mode == "all")
}
} }
//after rendering within a routed context, we need to scroll back to the top, and fetch the document title for history.pushState //after rendering within a routed context, we need to scroll back to the top, and fetch the document title for history.pushState
if (computePostRedrawHook) { if (computePostRedrawHook) {
@ -531,8 +546,9 @@ Mithril = m = new function app(window, undefined) {
var modes = {pathname: "", hash: "#", search: "?"} var modes = {pathname: "", hash: "#", search: "?"}
var redirect = function() {}, routeParams = {}, currentRoute var redirect = function() {}, routeParams = {}, currentRoute
m.route = function() { m.route = function() {
//m.route()
if (arguments.length === 0) return currentRoute if (arguments.length === 0) return currentRoute
else if (arguments.length === 3 && isStr(arguments[1])) { else if (arguments.length === 3 && type.call(arguments[1]) == sStr) {
var root = arguments[0], defaultRoute = arguments[1], router = arguments[2] var root = arguments[0], defaultRoute = arguments[1], router = arguments[2]
redirect = function(source) { redirect = function(source) {
var path = currentRoute = normalizeRoute(source) var path = currentRoute = normalizeRoute(source)
@ -549,20 +565,19 @@ Mithril = m = new function app(window, undefined) {
computePostRedrawHook = setScroll computePostRedrawHook = setScroll
window[listener]() window[listener]()
} }
//config: m.route
else if (arguments[0].addEventListener) { else if (arguments[0].addEventListener) {
var element = arguments[0] var element = arguments[0]
var isInitialized = arguments[1] var isInitialized = arguments[1]
var context = arguments[2] var context = arguments[2]
if (!isInitialized) { element.href = (m.route.mode !== 'pathname' ? window.location.pathname : '') + modes[m.route.mode] + this.attrs.href
context.href = element.getAttribute("href") element.removeEventListener("click", routeUnobtrusive)
element.href = (m.route.mode !== 'pathname' ? window.location.pathname : '') + modes[m.route.mode] + context.href element.addEventListener("click", routeUnobtrusive)
element.removeEventListener("click", routeUnobtrusive)
element.addEventListener("click", routeUnobtrusive)
}
} }
else if (isStr(arguments[0])) { //m.route(route)
else if (type.call(arguments[0]) == sStr) {
currentRoute = arguments[0] currentRoute = arguments[0]
var querystring = isObj(arguments[1]) ? buildQueryString(arguments[1]) : null var querystring = arguments[1] != null && type.call(arguments[1]) == sObj ? buildQueryString(arguments[1]) : null
if (querystring) currentRoute += (currentRoute.indexOf("?") === -1 ? "?" : "&") + querystring if (querystring) currentRoute += (currentRoute.indexOf("?") === -1 ? "?" : "&") + querystring
var shouldReplaceHistoryEntry = (arguments.length == 3 ? arguments[2] : arguments[1]) === true var shouldReplaceHistoryEntry = (arguments.length == 3 ? arguments[2] : arguments[1]) === true
@ -614,7 +629,8 @@ Mithril = m = new function app(window, undefined) {
if (e.preventDefault) e.preventDefault() if (e.preventDefault) e.preventDefault()
else e.returnValue = false else e.returnValue = false
var currentTarget = e.currentTarget || this var currentTarget = e.currentTarget || this
m.route(currentTarget[m.route.mode].slice(modes[m.route.mode].length)) var args = m.route.mode == "pathname" && currentTarget.search ? parseQueryString(currentTarget.search.slice(1)) : {}
m.route(currentTarget[m.route.mode].slice(modes[m.route.mode].length), args)
} }
function setScroll() { function setScroll() {
if (m.route.mode != "hash" && window.location.hash) window.location.hash = window.location.hash if (m.route.mode != "hash" && window.location.hash) window.location.hash = window.location.hash
@ -624,7 +640,7 @@ Mithril = m = new function app(window, undefined) {
var str = [] var str = []
for(var prop in object) { for(var prop in object) {
var key = prefix ? prefix + "[" + prop + "]" : prop, value = object[prop] var key = prefix ? prefix + "[" + prop + "]" : prop, value = object[prop]
str.push(isObj(value) ? buildQueryString(value, key) : encodeURIComponent(key) + "=" + encodeURIComponent(value)) str.push(value != null && type.call(value) == sObj ? buildQueryString(value, key) : encodeURIComponent(key) + "=" + encodeURIComponent(value))
} }
return str.join("&") return str.join("&")
} }
@ -651,7 +667,7 @@ Mithril = m = new function app(window, undefined) {
return deferred return deferred
} }
function propify(promise) { function propify(promise) {
prop = m.prop() var prop = m.prop()
promise.then(prop) promise.then(prop)
prop.then = function(resolve, reject) { prop.then = function(resolve, reject) {
return propify(promise.then(resolve, reject)) return propify(promise.then(resolve, reject))
@ -710,7 +726,7 @@ Mithril = m = new function app(window, undefined) {
} }
function thennable(then, successCallback, failureCallback, notThennableCallback) { function thennable(then, successCallback, failureCallback, notThennableCallback) {
if ((isObj(promiseValue) || isFn(promiseValue)) && isFn(then)) { if (((promiseValue != null && type.call(promiseValue) == sObj) || typeof promiseValue == sFn) && typeof then == sFn) {
try { try {
// count protects against abuse calls from spec checker // count protects against abuse calls from spec checker
var count = 0 var count = 0
@ -754,10 +770,10 @@ Mithril = m = new function app(window, undefined) {
fire() fire()
}, function() { }, function() {
try { try {
if (state == RESOLVING && isFn(successCallback)) { if (state == RESOLVING && typeof successCallback == sFn) {
promiseValue = successCallback(promiseValue) promiseValue = successCallback(promiseValue)
} }
else if (state == REJECTING && isFn(failureCallback)) { else if (state == REJECTING && typeof failureCallback == "function") {
promiseValue = failureCallback(promiseValue) promiseValue = failureCallback(promiseValue)
state = RESOLVING state = RESOLVING
} }
@ -783,7 +799,7 @@ Mithril = m = new function app(window, undefined) {
} }
} }
m.deferred.onerror = function(e) { m.deferred.onerror = function(e) {
if (type(e) == "[object Error]" && !e.constructor.toString().match(/ Error/)) throw e if (type.call(e) == "[object Error]" && !e.constructor.toString().match(/ Error/)) throw e
} }
m.sync = function(args) { m.sync = function(args) {
@ -808,7 +824,7 @@ Mithril = m = new function app(window, undefined) {
args[i].then(synchronizer(i, true), synchronizer(i, false)) args[i].then(synchronizer(i, true), synchronizer(i, false))
} }
} }
else deferred.resolve() else deferred.resolve([])
return deferred.promise return deferred.promise
} }
@ -871,22 +887,23 @@ Mithril = m = new function app(window, undefined) {
if (options.deserialize == JSON.parse) { if (options.deserialize == JSON.parse) {
xhr.setRequestHeader("Accept", "application/json, text/*"); xhr.setRequestHeader("Accept", "application/json, text/*");
} }
if (isFn(options.config)) { if (typeof options.config == sFn) {
var maybeXhr = options.config(xhr, options) var maybeXhr = options.config(xhr, options)
if (maybeXhr != null) xhr = maybeXhr if (maybeXhr != null) xhr = maybeXhr
} }
if (options.data && (type.call(options.data) != sStr && options.data.constructor != window.FormData)) throw "Request data should be either be a string or FormData. Check the `serialize` option in `m.request`"
xhr.send(options.method == "GET" || !options.data ? "" : options.data) xhr.send(options.method == "GET" || !options.data ? "" : options.data)
return xhr return xhr
} }
} }
function bindData(xhrOptions, data, serialize) { function bindData(xhrOptions, data, serialize) {
if (data && Object.keys(data).length > 0) { if (xhrOptions.method == "GET" && xhrOptions.dataType != "jsonp") {
if (xhrOptions.method == "GET" && xhrOptions.dataType != "jsonp") { var prefix = xhrOptions.url.indexOf("?") < 0 ? "?" : "&"
xhrOptions.url = xhrOptions.url + (xhrOptions.url.indexOf("?") < 0 ? "?" : "&") + buildQueryString(data) var querystring = buildQueryString(data)
} xhrOptions.url = xhrOptions.url + (querystring ? prefix + querystring : "")
else xhrOptions.data = serialize(data)
} }
else xhrOptions.data = serialize(data)
return xhrOptions return xhrOptions
} }
function parameterizeUrl(url, data) { function parameterizeUrl(url, data) {
@ -918,7 +935,7 @@ Mithril = m = new function app(window, undefined) {
var unwrap = (e.type == "load" ? xhrOptions.unwrapSuccess : xhrOptions.unwrapError) || identity var unwrap = (e.type == "load" ? xhrOptions.unwrapSuccess : xhrOptions.unwrapError) || identity
var response = unwrap(deserialize(extract(e.target, xhrOptions))) var response = unwrap(deserialize(extract(e.target, xhrOptions)))
if (e.type == "load") { if (e.type == "load") {
if (isArr(response) && xhrOptions.type) { if (type.call(response) == sArr && xhrOptions.type) {
for (var i = 0; i < response.length; i++) response[i] = new xhrOptions.type(response[i]) for (var i = 0; i < response.length; i++) response[i] = new xhrOptions.type(response[i])
} }
else if (xhrOptions.type) response = new xhrOptions.type(response) else if (xhrOptions.type) response = new xhrOptions.type(response)
@ -932,6 +949,7 @@ Mithril = m = new function app(window, undefined) {
if (xhrOptions.background !== true) m.endComputation() if (xhrOptions.background !== true) m.endComputation()
} }
ajax(xhrOptions) ajax(xhrOptions)
deferred.promise(xhrOptions.initialValue)
return deferred.promise return deferred.promise
} }
@ -948,6 +966,9 @@ if (typeof define == "function" && define.amd) define(function() {return m})
;;; ;;;
//make "use strict" and nodejs happy
var window = this
//test reporting for saucelabs //test reporting for saucelabs
if (typeof window != "undefined") { if (typeof window != "undefined") {
window.global_test_results = { window.global_test_results = {
@ -969,7 +990,7 @@ function test(condition) {
var result = true var result = true
test.total++ test.total++
if (this.performance != null && performance.now) { if (typeof performance != "undefined" && performance.now) {
start = performance.now() start = performance.now()
} }
try { try {
@ -980,11 +1001,11 @@ function test(condition) {
console.error(e) console.error(e)
test.failures.push(condition) test.failures.push(condition)
} }
if (this.performance != null && performance.now) { if (typeof performance != "undefined" && performance.now) {
duration = performance.now() - start duration = performance.now() - start
} }
test_obj = { window.test_obj = {
name: "" + test.total, name: "" + test.total,
result: result, result: result,
duration: duration duration: duration
@ -992,7 +1013,7 @@ function test(condition) {
if (typeof window != "undefined") { if (typeof window != "undefined") {
if (!result) { if (!result) {
window.global_test_results.tests.push(test_obj) window.global_test_results.tests.push(window.test_obj)
} }
window.global_test_results.duration += duration window.global_test_results.duration += duration
@ -1961,6 +1982,11 @@ function testMithril(mock) {
m.render(root, new Field()) m.render(root, new Field())
return root.childNodes.length == 1 return root.childNodes.length == 1
}) })
test(function() {
var root = mock.document.createElement("div")
m.render(root, {foo: 123})
return root.childNodes.length == 0
})
//end m.render //end m.render
//m.redraw //m.redraw
@ -2756,6 +2782,28 @@ function testMithril(mock) {
}) })
return value == "foo+bar" return value == "foo+bar"
}) })
test(function() {
mock.requestAnimationFrame.$resolve()
mock.location.search = "?"
var root = mock.document.createElement("div")
var a = {}
a.controller = function() {m.route("/b")}
a.view = function() {return "a"}
var b = {}
b.controller = function() {}
b.view = function(ctrl) {return "b"}
m.route(root, "/a", {
"/a": a,
"/b": b
})
mock.requestAnimationFrame.$resolve()
return root.childNodes[0].nodeValue == "b"
})
//end m.route //end m.route
//m.prop //m.prop
@ -2846,6 +2894,18 @@ function testMithril(mock) {
xhr.onreadystatechange() xhr.onreadystatechange()
return xhr.$headers["Content-Type"] === undefined return xhr.$headers["Content-Type"] === undefined
}) })
test(function() {
var prop = m.request({method: "POST", url: "test", initialValue: "foo"})
var initialValue = prop();
mock.XMLHttpRequest.$instances.pop().onreadystatechange()
return initialValue === "foo"
})
test(function() {
var prop = m.request({method: "POST", url: "test", initialValue: "foo"}).then(function(value) {return "bar"})
mock.XMLHttpRequest.$instances.pop().onreadystatechange()
return prop() === "bar"
})
// m.request over jsonp // m.request over jsonp
test(function(){ test(function(){
@ -3136,6 +3196,11 @@ function testMithril(mock) {
m.sync([]).then(function() {value = 2}) m.sync([]).then(function() {value = 2})
return value == 2 return value == 2
}) })
test(function() {
var success
m.sync([]).then(function(value) {success = value instanceof Array})
return success
})
//m.startComputation/m.endComputation //m.startComputation/m.endComputation
test(function() { test(function() {

View file

@ -949,7 +949,7 @@ Mithril = m = new function app(window, undefined) {
if (xhrOptions.background !== true) m.endComputation() if (xhrOptions.background !== true) m.endComputation()
} }
ajax(xhrOptions) ajax(xhrOptions)
deferred.promise(xhrOptions.default) deferred.promise(xhrOptions.initialValue)
return deferred.promise return deferred.promise
} }

View file

@ -1688,11 +1688,14 @@ function testMithril(mock) {
return xhr.$headers["Content-Type"] === undefined return xhr.$headers["Content-Type"] === undefined
}) })
test(function() { test(function() {
var prop = m.request({method: "POST", url: "test", default: "foo"}) var prop = m.request({method: "POST", url: "test", initialValue: "foo"})
return prop() === "foo" var initialValue = prop();
mock.XMLHttpRequest.$instances.pop().onreadystatechange()
return initialValue === "foo"
}) })
test(function() { test(function() {
var prop = m.request({method: "POST", url: "test", default: "foo"}).then(function(value) {return "bar"}) var prop = m.request({method: "POST", url: "test", initialValue: "foo"}).then(function(value) {return "bar"})
mock.XMLHttpRequest.$instances.pop().onreadystatechange() mock.XMLHttpRequest.$instances.pop().onreadystatechange()
return prop() === "bar" return prop() === "bar"
}) })