/*! * TableSorter 2.17.8 min - Client-side table sorting with ease! * Copyright (c) 2007 Christian Bach */ !function(h){h.extend({tablesorter:new function(){function d(){var b=arguments[0],a=1':"";n.$headers=h(b).find(n.selectorHeaders).each(function(k){c=h(this);a=g.getColumnData(b,n.headers,k,!0);n.headerContent[k]=h(this).html();""!==n.headerTemplate&&(l=n.headerTemplate.replace(/\{content\}/g,h(this).html()).replace(/\{icon\}/g, e),n.onRenderTemplate&&(f=n.onRenderTemplate.apply(c,[k,l]))&&"string"===typeof f&&(l=f),h(this).html('
'+l+"
"));n.onRenderHeader&&n.onRenderHeader.apply(c,[k]);this.column=parseInt(h(this).attr("data-column"),10);this.order=D(g.getData(c,a,"sortInitialOrder")||n.sortInitialOrder)?[1,0,2]:[0,1,2];this.count=-1;this.lockedOrder=!1;x=g.getData(c,a,"lockedOrder")||!1;"undefined"!==typeof x&&!1!==x&&(this.order=this.lockedOrder=D(x)?[1,1,1]:[0,0,0]);c.addClass(g.css.header+ " "+n.cssHeader);n.headerList[k]=this;c.parent().addClass(g.css.headerRow+" "+n.cssHeaderRow).attr("role","row");n.tabIndex&&c.attr("tabindex",0)}).attr({scope:"col",role:"columnheader"});H(b);n.debug&&(q("Built headers:",k),d(n.$headers))}function C(b,a,c){var f=b.config;f.$table.find(f.selectorRemove).remove();v(b);w(b);I(f.$table,a,c)}function H(b){var a,c,f,e=b.config;e.$headers.each(function(l,d){c=h(d);f=g.getColumnData(b,e.headers,l,!0);a="false"===g.getData(d,f,"sorter")||"false"===g.getData(d, f,"parser");d.sortDisabled=a;c[a?"addClass":"removeClass"]("sorter-false").attr("aria-disabled",""+a);b.id&&(a?c.removeAttr("aria-controls"):c.attr("aria-controls",b.id))})}function F(b){var a,c,f=b.config,e=f.sortList,l=e.length,d=g.css.sortNone+" "+f.cssNone,k=[g.css.sortAsc+" "+f.cssAsc,g.css.sortDesc+" "+f.cssDesc],n=["ascending","descending"],m=h(b).find("tfoot tr").children().add(f.$extraHeaders).removeClass(k.join(" "));f.$headers.removeClass(k.join(" ")).addClass(d).attr("aria-sort","none"); for(a=0;a"),c=h(b).width(),h(b.tBodies).not("."+f.cssInfoBlock).find("tr:first").children(":visible").each(function(){a.append(h("").css("width",parseInt(h(this).width()/c*1E3,10)/10+"%"))}),f.$table.prepend(a))}function P(b,a){var c,f,e,l,g,k=b.config,d=a||k.sortList;k.sortList= [];h.each(d,function(b,a){l=parseInt(a[0],10);if(e=k.$headers.filter('[data-column="'+l+'"]:last')[0]){f=(f=(""+a[1]).match(/^(1|d|s|o|n)/))?f[0]:"";switch(f){case "1":case "d":f=1;break;case "s":f=g||0;break;case "o":c=e.order[(g||0)%(k.sortReset?3:2)];f=0===c?1:1===c?0:2;break;case "n":e.count+=1;f=e.order[e.count%(k.sortReset?3:2)];break;default:f=0}g=0===b?f:g;c=[l,parseInt(f,10)||0];k.sortList.push(c);f=h.inArray(c[1],e.order);e.count=0<=f?f:c[1]%(k.sortReset?3:2)}})}function Q(b,a){return b&& b[a]?b[a].type||"":""}function L(b,a,c){if(b.isUpdating)return setTimeout(function(){L(b,a,c)},50);var f,e,l,d,k=b.config,n=!c[k.sortMultiSortKey],m=k.$table;m.trigger("sortStart",b);a.count=c[k.sortResetKey]?2:(a.count+1)%(k.sortReset?3:2);k.sortRestart&&(e=a,k.$headers.each(function(){this===e||!n&&h(this).is("."+g.css.sortDesc+",."+g.css.sortAsc)||(this.count=-1)}));e=a.column;if(n){k.sortList=[];if(null!==k.sortForce)for(f=k.sortForce,l=0;lf&&(k.sortList.push([e,f]),1f&& (k.sortList.push([e,f]),1 thead th, > thead td",selectorSort:"th, td",selectorRemove:".remove-me", debug:!1,headerList:[],empties:{},strings:{},parsers:[]};g.css={table:"tablesorter",cssHasChild:"tablesorter-hasChildRow",childRow:"tablesorter-childRow",header:"tablesorter-header",headerRow:"tablesorter-headerRow",headerIn:"tablesorter-header-inner",icon:"tablesorter-icon",info:"tablesorter-infoOnly",processing:"tablesorter-processing",sortAsc:"tablesorter-headerAsc",sortDesc:"tablesorter-headerDesc",sortNone:"tablesorter-headerUnSorted"};g.language={sortAsc:"Ascending sort applied, ",sortDesc:"Descending sort applied, ", sortNone:"No sort applied, ",nextAsc:"activate to apply an ascending sort",nextDesc:"activate to apply a descending sort",nextNone:"activate to remove the sort"};g.log=d;g.benchmark=q;g.construct=function(b){return this.each(function(){var a=h.extend(!0,{},g.defaults,b);a.originalSettings=b;!this.hasInitialized&&g.buildTable&&"TABLE"!==this.tagName?g.buildTable(this,a):g.setup(this,a)})};g.setup=function(b,a){if(!b||!b.tHead||0===b.tBodies.length||!0===b.hasInitialized)return a.debug?d("ERROR: stopping initialization! No table, thead, tbody or tablesorter has already been initialized"): "";var c="",f=h(b),e=h.metadata;b.hasInitialized=!1;b.isProcessing=!0;b.config=a;h.data(b,"tablesorter",a);a.debug&&h.data(b,"startoveralltimer",new Date);a.supportsDataObject=function(a){a[0]=parseInt(a[0],10);return 1'),c=h.fn.detach?a.detach():a.remove();c=h(b).find("span.tablesorter-savemyplace");a.insertAfter(c);c.remove();b.isProcessing=!1};g.clearTableBody=function(b){h(b)[0].config.$tbodies.children().detach()};g.bindEvents=function(b,a,c){b=h(b)[0];var f,e=b.config;!0!==c&&(e.$extraHeaders=e.$extraHeaders? e.$extraHeaders.add(a):a);a.find(e.selectorSort).add(a.filter(e.selectorSort)).unbind(["mousedown","mouseup","sort","keyup",""].join(e.namespace+" ")).bind(["mousedown","mouseup","sort","keyup",""].join(e.namespace+" "),function(c,d){var g;g=c.type;if(!(1!==(c.which||c.button)&&!/sort|keyup/.test(g)||"keyup"===g&&13!==c.which||"mouseup"===g&&!0!==d&&250<(new Date).getTime()-f)){if("mousedown"===g)return f=(new Date).getTime(),/(input|select|button|textarea)/i.test(c.target.tagName)?"":!e.cancelSelection; e.delayInit&&p(e.cache)&&w(b);g=h.fn.closest?h(this).closest("th, td")[0]:/TH|TD/.test(this.tagName)?this:h(this).parents("th, td")[0];g=e.$headers[a.index(g)];g.sortDisabled||L(b,g,c)}});e.cancelSelection&&a.attr("unselectable","on").bind("selectstart",!1).css({"user-select":"none",MozUserSelect:"none"})};g.restoreHeaders=function(b){var a=h(b)[0].config;a.$table.find(a.selectorHeaders).each(function(b){h(this).find("."+g.css.headerIn).length&&h(this).html(a.headerContent[b])})};g.destroy=function(b, a,c){b=h(b)[0];if(b.hasInitialized){g.refreshWidgets(b,!0,!0);var f=h(b),e=b.config,d=f.find("thead:first"),q=d.find("tr."+g.css.headerRow).removeClass(g.css.headerRow+" "+e.cssHeaderRow),k=f.find("tfoot:first > tr").children("th, td");!1===a&&0<=h.inArray("uitheme",e.widgets)&&(f.trigger("applyWidgetId",["uitheme"]),f.trigger("applyWidgetId",["zebra"]));d.find("tr").not(q).remove();f.removeData("tablesorter").unbind("sortReset update updateAll updateRows updateCell addRows updateComplete sorton appendCache updateCache applyWidgetId applyWidgets refreshWidgets destroy mouseup mouseleave keypress sortBegin sortEnd resetToLoadState ".split(" ").join(e.namespace+ " "));e.$headers.add(k).removeClass([g.css.header,e.cssHeader,e.cssAsc,e.cssDesc,g.css.sortAsc,g.css.sortDesc,g.css.sortNone].join(" ")).removeAttr("data-column").removeAttr("aria-label").attr("aria-disabled","true");q.find(e.selectorSort).unbind(["mousedown","mouseup","keypress",""].join(e.namespace+" "));g.restoreHeaders(b);f.toggleClass(g.css.table+" "+e.tableClass+" tablesorter-"+e.theme,!1===a);b.hasInitialized=!1;delete b.config.cache;"function"===typeof c&&c(b)}};g.regex={chunk:/(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi, chunks:/(^\\0|\\0$)/,hex:/^0x[0-9a-f]+$/i};g.sortNatural=function(b,a){if(b===a)return 0;var c,f,e,d,h,k;f=g.regex;if(f.hex.test(a)){c=parseInt(b.match(f.hex),16);e=parseInt(a.match(f.hex),16);if(ce)return 1}c=b.replace(f.chunk,"\\0$1\\0").replace(f.chunks,"").split("\\0");f=a.replace(f.chunk,"\\0$1\\0").replace(f.chunks,"").split("\\0");k=Math.max(c.length,f.length);for(h=0;hd)return 1}return 0};g.sortNaturalAsc=function(b,a,c,f,e){if(b===a)return 0;c=e.string[e.empties[c]||e.emptyTo];return""===b&&0!==c?"boolean"===typeof c?c?-1:1:-c||-1:""===a&&0!==c?"boolean"===typeof c?c?1:-1:c||1:g.sortNatural(b,a)};g.sortNaturalDesc=function(b,a,c,f,e){if(b===a)return 0;c=e.string[e.empties[c]||e.emptyTo];return""===b&&0!==c?"boolean"===typeof c?c?-1:1:c||1:""===a&&0!==c?"boolean"===typeof c?c? 1:-1:-c||-1:g.sortNatural(a,b)};g.sortText=function(b,a){return b>a?1:bh.inArray(q[f].id,l))&&(e.debug&&d('Refeshing widgets: Removing "'+q[f].id+'"'),q[f].hasOwnProperty("remove")&&e.widgetInit[q[f].id]&&(q[f].remove(b, e,e.widgetOptions),e.widgetInit[q[f].id]=!1));!0!==c&&g.applyWidget(b,a)};g.getData=function(b,a,c){var d="";b=h(b);var e,g;if(!b.length)return"";e=h.metadata?b.metadata():!1;g=" "+(b.attr("class")||"");"undefined"!==typeof b.data(c)||"undefined"!==typeof b.data(c.toLowerCase())?d+=b.data(c)||b.data(c.toLowerCase()):e&&"undefined"!==typeof e[c]?d+=e[c]:a&&"undefined"!==typeof a[c]?d+=a[c]:" "!==g&&g.match(" "+c+"-")&&(d=g.match(new RegExp("\\s"+c+"-([\\w-]+)"))[1]||"");return h.trim(d)};g.formatFloat= function(b,a){if("string"!==typeof b||""===b)return b;var c;b=(a&&a.config?!1!==a.config.usNumberFormat:"undefined"!==typeof a?a:1)?b.replace(/,/g,""):b.replace(/[\s|\.]/g,"").replace(/,/g,".");/^\s*\([.\d]+\)/.test(b)&&(b=b.replace(/^\s*\(([.\d]+)\)/,"-$1"));c=parseFloat(b);return isNaN(c)?h.trim(b):c};g.isDigit=function(b){return isNaN(b)?/^[\-+(]?\d+[)]?$/.test(b.toString().replace(/[,.'"\s]/g,"")):!0}}});var r=h.tablesorter;h.fn.extend({tablesorter:r.construct});r.addParser({id:"no-parser",is:function(){return!1}, format:function(){return""},type:"text"});r.addParser({id:"text",is:function(){return!0},format:function(d,q){var p=q.config;d&&(d=h.trim(p.ignoreCase?d.toLocaleLowerCase():d),d=p.sortLocaleCompare?r.replaceAccents(d):d);return d},type:"text"});r.addParser({id:"digit",is:function(d){return r.isDigit(d)},format:function(d,q){var p=r.formatFloat((d||"").replace(/[^\w,. \-()]/g,""),q);return d&&"number"===typeof p?p:d?h.trim(d&&q.config.ignoreCase?d.toLocaleLowerCase():d):d},type:"numeric"});r.addParser({id:"currency", is:function(d){return/^\(?\d+[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]|[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]\d+\)?$/.test((d||"").replace(/[+\-,. ]/g,""))},format:function(d,q){var p=r.formatFloat((d||"").replace(/[^\w,. \-()]/g,""),q);return d&&"number"===typeof p?p:d?h.trim(d&&q.config.ignoreCase?d.toLocaleLowerCase():d):d},type:"numeric"});r.addParser({id:"ipAddress",is:function(d){return/^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/.test(d)},format:function(d,h){var p,y=d?d.split("."):"",v="",w=y.length; for(p=0;pd.length},format:function(d,h){return d?r.formatFloat(d.replace(/%/g,""),h):d},type:"numeric"});r.addParser({id:"usLongDate",is:function(d){return/^[A-Z]{3,10}\.?\s+\d{1,2},?\s+(\d{4})(\s+\d{1,2}:\d{2}(:\d{2})?(\s+[AP]M)?)?$/i.test(d)||/^\d{1,2}\s+[A-Z]{3,10}\s+\d{4}/i.test(d)},format:function(d,h){return d?r.formatFloat((new Date(d.replace(/(\S)([AP]M)$/i,"$1 $2"))).getTime()||d,h):d},type:"numeric"});r.addParser({id:"shortDate",is:function(d){return/(^\d{1,2}[\/\s]\d{1,2}[\/\s]\d{4})|(^\d{4}[\/\s]\d{1,2}[\/\s]\d{1,2})/.test((d|| "").replace(/\s+/g," ").replace(/[\-.,]/g,"/"))},format:function(d,h,p,y){if(d){p=h.config;var v=p.$headers.filter("[data-column="+y+"]:last");y=v.length&&v[0].dateFormat||r.getData(v,r.getColumnData(h,p.headers,y),"dateFormat")||p.dateFormat;d=d.replace(/\s+/g," ").replace(/[\-.,]/g,"/");"mmddyyyy"===y?d=d.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/,"$3/$1/$2"):"ddmmyyyy"===y?d=d.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/,"$3/$2/$1"):"yyyymmdd"===y&&(d=d.replace(/(\d{4})[\/\s](\d{1,2})[\/\s](\d{1,2})/, "$1/$2/$3"))}return d?r.formatFloat((new Date(d)).getTime()||d,h):d},type:"numeric"});r.addParser({id:"time",is:function(d){return/^(([0-2]?\d:[0-5]\d)|([0-1]?\d:[0-5]\d\s?([AP]M)))$/i.test(d)},format:function(d,h){return d?r.formatFloat((new Date("2000/01/01 "+d.replace(/(\S)([AP]M)$/i,"$1 $2"))).getTime()||d,h):d},type:"numeric"});r.addParser({id:"metadata",is:function(){return!1},format:function(d,q,p){d=q.config;d=d.parserMetadataName?d.parserMetadataName:"sortValue";return h(p).metadata()[d]}, type:"numeric"});r.addWidget({id:"zebra",priority:90,format:function(d,q,p){var y,v,w,z,D,E=new RegExp(q.cssChildRow,"i"),C=q.$tbodies;q.debug&&(D=new Date);for(d=0;d= e) { d.appendTo($("tbody", a)) } else if (c == 0) { d.prependTo($("tbody", a)) } else { d.insertBefore($("tbody tr:eq(" + c + ")", a)) } } }) } } } }) /*! * jScroll - jQuery Plugin for Infinite Scrolling / Auto-Paging * http://jscroll.com/ * * Copyright 2011-2013, Philip Klauzinski * http://klauzinski.com/ * Dual licensed under the MIT and GPL Version 2 licenses. * http://jscroll.com/#license * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl-2.0.html * * @author Philip Klauzinski * @version 2.3.4 * @requires jQuery v1.4.3+ * @preserve */ !function(a){"use strict";a.jscroll={defaults:{debug:!1,autoTrigger:!0,autoTriggerUntil:!1,loadingHtml:"Loading...",padding:0,nextSelector:"a:last",contentSelector:"",pagingSelector:"",callback:!1}};var b=function(b,c){var d=b.data("jscroll"),e="function"==typeof c?{callback:c}:c,f=a.extend({},a.jscroll.defaults,e,d||{}),g="visible"===b.css("overflow-y"),h=b.find(f.nextSelector).first(),i=a(window),j=a("body"),k=g?i:b,l=a.trim(h.attr("href")+" "+f.contentSelector),m=function(){var b=a(f.loadingHtml).filter("img").attr("src");if(b){var c=new Image;c.src=b}},n=function(){b.find(".jscroll-inner").length||b.contents().wrapAll('
')},o=function(a){var b;f.pagingSelector?a.closest(f.pagingSelector).hide():(b=a.parent().not(".jscroll-inner,.jscroll-added").addClass("jscroll-next-parent").hide(),b.length||a.wrap('
').parent().hide())},p=function(){return k.unbind(".jscroll").removeData("jscroll").find(".jscroll-inner").children().unwrap().filter(".jscroll-added").children().unwrap()},q=function(){n();var a=b.find("div.jscroll-inner").first(),c=b.data("jscroll"),d=parseInt(b.css("borderTopWidth"),10),e=isNaN(d)?0:d,h=parseInt(b.css("paddingTop"),10)+e,i=g?k.scrollTop():b.offset().top,j=a.length?a.offset().top:0,l=Math.ceil(i-j+k.height()+h);return!c.waiting&&l+f.padding>=a.outerHeight()?(u("info","jScroll:",a.outerHeight()-l,"from bottom. Loading next request..."),t()):void 0},r=function(a){return a=a||b.data("jscroll"),a&&a.nextHref?(s(),!0):(u("warn","jScroll: nextSelector not found - destroying"),p(),!1)},s=function(){var a=b.find(f.nextSelector).first();a.length&&(f.autoTrigger&&(f.autoTriggerUntil===!1||f.autoTriggerUntil>0)?(o(a),j.height()<=i.height()&&q(),k.unbind(".jscroll").bind("scroll.jscroll",function(){return q()}),f.autoTriggerUntil>0&&f.autoTriggerUntil--):(k.unbind(".jscroll"),a.bind("click.jscroll",function(){return o(a),t(),!1})))},t=function(){var c=b.find("div.jscroll-inner").first(),d=b.data("jscroll");return d.waiting=!0,c.append('
').children(".jscroll-added").last().html('
'+f.loadingHtml+"
"),b.animate({scrollTop:c.outerHeight()},0,function(){c.find("div.jscroll-added").last().load(d.nextHref,function(c,e){if("error"===e)return p();var g=a(this).find(f.nextSelector).first();d.waiting=!1,d.nextHref=g.attr("href")?a.trim(g.attr("href")+" "+f.contentSelector):!1,a(".jscroll-next-parent",b).remove(),r(),f.callback&&f.callback.call(this),u("dir",d)})})},u=function(a){if(f.debug&&"object"==typeof console&&("object"==typeof a||"function"==typeof console[a]))if("object"==typeof a){var b=[];for(var c in a)"function"==typeof console[c]?(b=a[c].length?a[c]:[a[c]],console[c].apply(console,b)):console.log.apply(console,b)}else console[a].apply(console,Array.prototype.slice.call(arguments,1))};return b.data("jscroll",a.extend({},d,{initialized:!0,waiting:!1,nextHref:l})),n(),m(),s(),a.extend(b.jscroll,{destroy:p}),b};a.fn.jscroll=function(c){return this.each(function(){var d,e=a(this),f=e.data("jscroll");f&&f.initialized||(d=new b(e,c))})}}(jQuery); /*! js-cookie v2.2.1 | MIT */ !function(a){var b;if("function"==typeof define&&define.amd&&(define(a),b=!0),"object"==typeof exports&&(module.exports=a(),b=!0),!b){var c=window.Cookies,d=window.Cookies=a();d.noConflict=function(){return window.Cookies=c,d}}}(function(){function a(){for(var a=0,b={};a tag) - put directly in global namespace factory(window['ko'] = {}); } }(function(koExports, require){ // Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler). // In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable. var ko = typeof koExports !== 'undefined' ? koExports : {}; // Google Closure Compiler helpers (used only to make the minified file smaller) ko.exportSymbol = function(koPath, object) { var tokens = koPath.split("."); // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable) // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko) var target = ko; for (var i = 0; i < tokens.length - 1; i++) target = target[tokens[i]]; target[tokens[tokens.length - 1]] = object; }; ko.exportProperty = function(owner, publicName, object) { owner[publicName] = object; }; ko.version = "3.2.0"; ko.exportSymbol('version', ko.version); ko.utils = (function () { function objectForEach(obj, action) { for (var prop in obj) { if (obj.hasOwnProperty(prop)) { action(prop, obj[prop]); } } } function extend(target, source) { if (source) { for(var prop in source) { if(source.hasOwnProperty(prop)) { target[prop] = source[prop]; } } } return target; } function setPrototypeOf(obj, proto) { obj.__proto__ = proto; return obj; } var canSetPrototype = ({ __proto__: [] } instanceof Array); // Represent the known event types in a compact way, then at runtime transform it into a hash with event name as key (for fast lookup) var knownEvents = {}, knownEventTypesByEventName = {}; var keyEventTypeName = (navigator && /Firefox\/2/i.test(navigator.userAgent)) ? 'KeyboardEvent' : 'UIEvents'; knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress']; knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave']; objectForEach(knownEvents, function(eventType, knownEventsForType) { if (knownEventsForType.length) { for (var i = 0, j = knownEventsForType.length; i < j; i++) knownEventTypesByEventName[knownEventsForType[i]] = eventType; } }); var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406 // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness) // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10. // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser. // If there is a future need to detect specific versions of IE10+, we will amend this. var ieVersion = document && (function() { var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i'); // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment while ( div.innerHTML = '', iElems[0] ) {} return version > 4 ? version : undefined; }()); var isIe6 = ieVersion === 6, isIe7 = ieVersion === 7; function isClickOnCheckableElement(element, eventType) { if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false; if (eventType.toLowerCase() != "click") return false; var inputType = element.type; return (inputType == "checkbox") || (inputType == "radio"); } return { fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/], arrayForEach: function (array, action) { for (var i = 0, j = array.length; i < j; i++) action(array[i], i); }, arrayIndexOf: function (array, item) { if (typeof Array.prototype.indexOf == "function") return Array.prototype.indexOf.call(array, item); for (var i = 0, j = array.length; i < j; i++) if (array[i] === item) return i; return -1; }, arrayFirst: function (array, predicate, predicateOwner) { for (var i = 0, j = array.length; i < j; i++) if (predicate.call(predicateOwner, array[i], i)) return array[i]; return null; }, arrayRemoveItem: function (array, itemToRemove) { var index = ko.utils.arrayIndexOf(array, itemToRemove); if (index > 0) { array.splice(index, 1); } else if (index === 0) { array.shift(); } }, arrayGetDistinctValues: function (array) { array = array || []; var result = []; for (var i = 0, j = array.length; i < j; i++) { if (ko.utils.arrayIndexOf(result, array[i]) < 0) result.push(array[i]); } return result; }, arrayMap: function (array, mapping) { array = array || []; var result = []; for (var i = 0, j = array.length; i < j; i++) result.push(mapping(array[i], i)); return result; }, arrayFilter: function (array, predicate) { array = array || []; var result = []; for (var i = 0, j = array.length; i < j; i++) if (predicate(array[i], i)) result.push(array[i]); return result; }, arrayPushAll: function (array, valuesToPush) { if (valuesToPush instanceof Array) array.push.apply(array, valuesToPush); else for (var i = 0, j = valuesToPush.length; i < j; i++) array.push(valuesToPush[i]); return array; }, addOrRemoveItem: function(array, value, included) { var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.peekObservable(array), value); if (existingEntryIndex < 0) { if (included) array.push(value); } else { if (!included) array.splice(existingEntryIndex, 1); } }, canSetPrototype: canSetPrototype, extend: extend, setPrototypeOf: setPrototypeOf, setPrototypeOfOrExtend: canSetPrototype ? setPrototypeOf : extend, objectForEach: objectForEach, objectMap: function(source, mapping) { if (!source) return source; var target = {}; for (var prop in source) { if (source.hasOwnProperty(prop)) { target[prop] = mapping(source[prop], prop, source); } } return target; }, emptyDomNode: function (domNode) { while (domNode.firstChild) { ko.removeNode(domNode.firstChild); } }, moveCleanedNodesToContainerElement: function(nodes) { // Ensure it's a real array, as we're about to reparent the nodes and // we don't want the underlying collection to change while we're doing that. var nodesArray = ko.utils.makeArray(nodes); var container = document.createElement('div'); for (var i = 0, j = nodesArray.length; i < j; i++) { container.appendChild(ko.cleanNode(nodesArray[i])); } return container; }, cloneNodes: function (nodesArray, shouldCleanNodes) { for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) { var clonedNode = nodesArray[i].cloneNode(true); newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode); } return newNodesArray; }, setDomNodeChildren: function (domNode, childNodes) { ko.utils.emptyDomNode(domNode); if (childNodes) { for (var i = 0, j = childNodes.length; i < j; i++) domNode.appendChild(childNodes[i]); } }, replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) { var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray; if (nodesToReplaceArray.length > 0) { var insertionPoint = nodesToReplaceArray[0]; var parent = insertionPoint.parentNode; for (var i = 0, j = newNodesArray.length; i < j; i++) parent.insertBefore(newNodesArray[i], insertionPoint); for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) { ko.removeNode(nodesToReplaceArray[i]); } } }, fixUpContinuousNodeArray: function(continuousNodeArray, parentNode) { // Before acting on a set of nodes that were previously outputted by a template function, we have to reconcile // them against what is in the DOM right now. It may be that some of the nodes have already been removed, or that // new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding. // So, this function translates the old "map" output array into its best guess of the set of current DOM nodes. // // Rules: // [A] Any leading nodes that have been removed should be ignored // These most likely correspond to memoization nodes that were already removed during binding // See https://github.com/SteveSanderson/knockout/pull/440 // [B] We want to output a continuous series of nodes. So, ignore any nodes that have already been removed, // and include any nodes that have been inserted among the previous collection if (continuousNodeArray.length) { // The parent node can be a virtual element; so get the real parent node parentNode = (parentNode.nodeType === 8 && parentNode.parentNode) || parentNode; // Rule [A] while (continuousNodeArray.length && continuousNodeArray[0].parentNode !== parentNode) continuousNodeArray.shift(); // Rule [B] if (continuousNodeArray.length > 1) { var current = continuousNodeArray[0], last = continuousNodeArray[continuousNodeArray.length - 1]; // Replace with the actual new continuous node set continuousNodeArray.length = 0; while (current !== last) { continuousNodeArray.push(current); current = current.nextSibling; if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario) return; } continuousNodeArray.push(last); } } return continuousNodeArray; }, setOptionNodeSelectionState: function (optionNode, isSelected) { // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser. if (ieVersion < 7) optionNode.setAttribute("selected", isSelected); else optionNode.selected = isSelected; }, stringTrim: function (string) { return string === null || string === undefined ? '' : string.trim ? string.trim() : string.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g, ''); }, stringStartsWith: function (string, startsWith) { string = string || ""; if (startsWith.length > string.length) return false; return string.substring(0, startsWith.length) === startsWith; }, domNodeIsContainedBy: function (node, containedByNode) { if (node === containedByNode) return true; if (node.nodeType === 11) return false; // Fixes issue #1162 - can't use node.contains for document fragments on IE8 if (containedByNode.contains) return containedByNode.contains(node.nodeType === 3 ? node.parentNode : node); if (containedByNode.compareDocumentPosition) return (containedByNode.compareDocumentPosition(node) & 16) == 16; while (node && node != containedByNode) { node = node.parentNode; } return !!node; }, domNodeIsAttachedToDocument: function (node) { return ko.utils.domNodeIsContainedBy(node, node.ownerDocument.documentElement); }, anyDomNodeIsAttachedToDocument: function(nodes) { return !!ko.utils.arrayFirst(nodes, ko.utils.domNodeIsAttachedToDocument); }, tagNameLower: function(element) { // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case. // Possible future optimization: If we know it's an element from an XHTML document (not HTML), // we don't need to do the .toLowerCase() as it will always be lower case anyway. return element && element.tagName && element.tagName.toLowerCase(); }, registerEventHandler: function (element, eventType, handler) { var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType]; if (!mustUseAttachEvent && jQueryInstance) { jQueryInstance(element)['bind'](eventType, handler); } else if (!mustUseAttachEvent && typeof element.addEventListener == "function") element.addEventListener(eventType, handler, false); else if (typeof element.attachEvent != "undefined") { var attachEventHandler = function (event) { handler.call(element, event); }, attachEventName = "on" + eventType; element.attachEvent(attachEventName, attachEventHandler); // IE does not dispose attachEvent handlers automatically (unlike with addEventListener) // so to avoid leaks, we have to remove them manually. See bug #856 ko.utils.domNodeDisposal.addDisposeCallback(element, function() { element.detachEvent(attachEventName, attachEventHandler); }); } else throw new Error("Browser doesn't support addEventListener or attachEvent"); }, triggerEvent: function (element, eventType) { if (!(element && element.nodeType)) throw new Error("element must be a DOM node when calling triggerEvent"); // For click events on checkboxes and radio buttons, jQuery toggles the element checked state *after* the // event handler runs instead of *before*. (This was fixed in 1.9 for checkboxes but not for radio buttons.) // IE doesn't change the checked state when you trigger the click event using "fireEvent". // In both cases, we'll use the click method instead. var useClickWorkaround = isClickOnCheckableElement(element, eventType); if (jQueryInstance && !useClickWorkaround) { jQueryInstance(element)['trigger'](eventType); } else if (typeof document.createEvent == "function") { if (typeof element.dispatchEvent == "function") { var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents"; var event = document.createEvent(eventCategory); event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element); element.dispatchEvent(event); } else throw new Error("The supplied element doesn't support dispatchEvent"); } else if (useClickWorkaround && element.click) { element.click(); } else if (typeof element.fireEvent != "undefined") { element.fireEvent("on" + eventType); } else { throw new Error("Browser doesn't support triggering events"); } }, unwrapObservable: function (value) { return ko.isObservable(value) ? value() : value; }, peekObservable: function (value) { return ko.isObservable(value) ? value.peek() : value; }, toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) { if (classNames) { var cssClassNameRegex = /\S+/g, currentClassNames = node.className.match(cssClassNameRegex) || []; ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) { ko.utils.addOrRemoveItem(currentClassNames, className, shouldHaveClass); }); node.className = currentClassNames.join(" "); } }, setTextContent: function(element, textContent) { var value = ko.utils.unwrapObservable(textContent); if ((value === null) || (value === undefined)) value = ""; // We need there to be exactly one child: a text node. // If there are no children, more than one, or if it's not a text node, // we'll clear everything and create a single text node. var innerTextNode = ko.virtualElements.firstChild(element); if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) { ko.virtualElements.setDomNodeChildren(element, [element.ownerDocument.createTextNode(value)]); } else { innerTextNode.data = value; } ko.utils.forceRefresh(element); }, setElementName: function(element, name) { element.name = name; // Workaround IE 6/7 issue // - https://github.com/SteveSanderson/knockout/issues/197 // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/ if (ieVersion <= 7) { try { element.mergeAttributes(document.createElement(""), false); } catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View" } }, forceRefresh: function(node) { // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209 if (ieVersion >= 9) { // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container var elem = node.nodeType == 1 ? node : node.parentNode; if (elem.style) elem.style.zoom = elem.style.zoom; } }, ensureSelectElementIsRenderedCorrectly: function(selectElement) { // Workaround for IE9 rendering bug - it doesn't reliably display all the text in dynamically-added select boxes unless you force it to re-render by updating the width. // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option) // Also fixes IE7 and IE8 bug that causes selects to be zero width if enclosed by 'if' or 'with'. (See issue #839) if (ieVersion) { var originalWidth = selectElement.style.width; selectElement.style.width = 0; selectElement.style.width = originalWidth; } }, range: function (min, max) { min = ko.utils.unwrapObservable(min); max = ko.utils.unwrapObservable(max); var result = []; for (var i = min; i <= max; i++) result.push(i); return result; }, makeArray: function(arrayLikeObject) { var result = []; for (var i = 0, j = arrayLikeObject.length; i < j; i++) { result.push(arrayLikeObject[i]); }; return result; }, isIe6 : isIe6, isIe7 : isIe7, ieVersion : ieVersion, getFormFields: function(form, fieldName) { var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea"))); var isMatchingField = (typeof fieldName == 'string') ? function(field) { return field.name === fieldName } : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate var matches = []; for (var i = fields.length - 1; i >= 0; i--) { if (isMatchingField(fields[i])) matches.push(fields[i]); }; return matches; }, parseJson: function (jsonString) { if (typeof jsonString == "string") { jsonString = ko.utils.stringTrim(jsonString); if (jsonString) { if (JSON && JSON.parse) // Use native parsing where available return JSON.parse(jsonString); return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers } } return null; }, stringifyJson: function (data, replacer, space) { // replacer and space are optional if (!JSON || !JSON.stringify) throw new Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js"); return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space); }, postJson: function (urlOrForm, data, options) { options = options || {}; var params = options['params'] || {}; var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost; var url = urlOrForm; // If we were given a form, use its 'action' URL and pick out any requested field values if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) { var originalForm = urlOrForm; url = originalForm.action; for (var i = includeFields.length - 1; i >= 0; i--) { var fields = ko.utils.getFormFields(originalForm, includeFields[i]); for (var j = fields.length - 1; j >= 0; j--) params[fields[j].name] = fields[j].value; } } data = ko.utils.unwrapObservable(data); var form = document.createElement("form"); form.style.display = "none"; form.action = url; form.method = "post"; for (var key in data) { // Since 'data' this is a model object, we include all properties including those inherited from its prototype var input = document.createElement("input"); input.type = "hidden"; input.name = key; input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key])); form.appendChild(input); } objectForEach(params, function(key, value) { var input = document.createElement("input"); input.type = "hidden"; input.name = key; input.value = value; form.appendChild(input); }); document.body.appendChild(form); options['submitter'] ? options['submitter'](form) : form.submit(); setTimeout(function () { form.parentNode.removeChild(form); }, 0); } } }()); ko.exportSymbol('utils', ko.utils); ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach); ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst); ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter); ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues); ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf); ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap); ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll); ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem); ko.exportSymbol('utils.extend', ko.utils.extend); ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost); ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields); ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable); ko.exportSymbol('utils.postJson', ko.utils.postJson); ko.exportSymbol('utils.parseJson', ko.utils.parseJson); ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler); ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson); ko.exportSymbol('utils.range', ko.utils.range); ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass); ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent); ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable); ko.exportSymbol('utils.objectForEach', ko.utils.objectForEach); ko.exportSymbol('utils.addOrRemoveItem', ko.utils.addOrRemoveItem); ko.exportSymbol('unwrap', ko.utils.unwrapObservable); // Convenient shorthand, because this is used so commonly if (!Function.prototype['bind']) { // Function.prototype.bind is a standard part of ECMAScript 5th Edition (December 2009, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf) // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js Function.prototype['bind'] = function (object) { var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift(); return function () { return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments))); }; }; } ko.utils.domData = new (function () { var uniqueId = 0; var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime(); var dataStore = {}; function getAll(node, createIfNotFound) { var dataStoreKey = node[dataStoreKeyExpandoPropertyName]; var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey]; if (!hasExistingDataStore) { if (!createIfNotFound) return undefined; dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++; dataStore[dataStoreKey] = {}; } return dataStore[dataStoreKey]; } return { get: function (node, key) { var allDataForNode = getAll(node, false); return allDataForNode === undefined ? undefined : allDataForNode[key]; }, set: function (node, key, value) { if (value === undefined) { // Make sure we don't actually create a new domData key if we are actually deleting a value if (getAll(node, false) === undefined) return; } var allDataForNode = getAll(node, true); allDataForNode[key] = value; }, clear: function (node) { var dataStoreKey = node[dataStoreKeyExpandoPropertyName]; if (dataStoreKey) { delete dataStore[dataStoreKey]; node[dataStoreKeyExpandoPropertyName] = null; return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended } return false; }, nextKey: function () { return (uniqueId++) + dataStoreKeyExpandoPropertyName; } }; })(); ko.exportSymbol('utils.domData', ko.utils.domData); ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully ko.utils.domNodeDisposal = new (function () { var domDataKey = ko.utils.domData.nextKey(); var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document function getDisposeCallbacksCollection(node, createIfNotFound) { var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey); if ((allDisposeCallbacks === undefined) && createIfNotFound) { allDisposeCallbacks = []; ko.utils.domData.set(node, domDataKey, allDisposeCallbacks); } return allDisposeCallbacks; } function destroyCallbacksCollection(node) { ko.utils.domData.set(node, domDataKey, undefined); } function cleanSingleNode(node) { // Run all the dispose callbacks var callbacks = getDisposeCallbacksCollection(node, false); if (callbacks) { callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves) for (var i = 0; i < callbacks.length; i++) callbacks[i](node); } // Erase the DOM data ko.utils.domData.clear(node); // Perform cleanup needed by external libraries (currently only jQuery, but can be extended) ko.utils.domNodeDisposal["cleanExternalData"](node); // Clear any immediate-child comment nodes, as these wouldn't have been found by // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements) if (cleanableNodeTypesWithDescendants[node.nodeType]) cleanImmediateCommentTypeChildren(node); } function cleanImmediateCommentTypeChildren(nodeWithChildren) { var child, nextChild = nodeWithChildren.firstChild; while (child = nextChild) { nextChild = child.nextSibling; if (child.nodeType === 8) cleanSingleNode(child); } } return { addDisposeCallback : function(node, callback) { if (typeof callback != "function") throw new Error("Callback must be a function"); getDisposeCallbacksCollection(node, true).push(callback); }, removeDisposeCallback : function(node, callback) { var callbacksCollection = getDisposeCallbacksCollection(node, false); if (callbacksCollection) { ko.utils.arrayRemoveItem(callbacksCollection, callback); if (callbacksCollection.length == 0) destroyCallbacksCollection(node); } }, cleanNode : function(node) { // First clean this node, where applicable if (cleanableNodeTypes[node.nodeType]) { cleanSingleNode(node); // ... then its descendants, where applicable if (cleanableNodeTypesWithDescendants[node.nodeType]) { // Clone the descendants list in case it changes during iteration var descendants = []; ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*")); for (var i = 0, j = descendants.length; i < j; i++) cleanSingleNode(descendants[i]); } } return node; }, removeNode : function(node) { ko.cleanNode(node); if (node.parentNode) node.parentNode.removeChild(node); }, "cleanExternalData" : function (node) { // Special support for jQuery here because it's so commonly used. // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData // so notify it to tear down any resources associated with the node & descendants here. if (jQueryInstance && (typeof jQueryInstance['cleanData'] == "function")) jQueryInstance['cleanData']([node]); } } })(); ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience ko.exportSymbol('cleanNode', ko.cleanNode); ko.exportSymbol('removeNode', ko.removeNode); ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal); ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback); ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback); (function () { var leadingCommentRegex = /^(\s*)/; function simpleHtmlParse(html) { // Based on jQuery's "clean" function, but only accounting for table-related elements. // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of // a descendant node. For example: "
abc
" will get parsed as "
abc
" // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present. // Trim whitespace, otherwise indexOf won't work as expected var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div"); // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "", "
"] || !tags.indexOf("", ""] || (!tags.indexOf("", ""] || /* anything else */ [0, "", ""]; // Go to html and back, then peel off extra wrappers // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness. var markup = "ignored
" + wrap[1] + html + wrap[2] + "
"; if (typeof window['innerShiv'] == "function") { div.appendChild(window['innerShiv'](markup)); } else { div.innerHTML = markup; } // Move to the right depth while (wrap[0]--) div = div.lastChild; return ko.utils.makeArray(div.lastChild.childNodes); } function jQueryHtmlParse(html) { // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API. if (jQueryInstance['parseHTML']) { return jQueryInstance['parseHTML'](html) || []; // Ensure we always return an array and never null } else { // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function. var elems = jQueryInstance['clean']([html]); // As of jQuery 1.7.1, jQuery parses the HTML by appending it to some dummy parent nodes held in an in-memory document fragment. // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time. // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment. if (elems && elems[0]) { // Find the top-most parent element that's a direct child of a document fragment var elem = elems[0]; while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */) elem = elem.parentNode; // ... then detach it if (elem.parentNode) elem.parentNode.removeChild(elem); } return elems; } } ko.utils.parseHtmlFragment = function(html) { return jQueryInstance ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases. }; ko.utils.setHtml = function(node, html) { ko.utils.emptyDomNode(node); // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it html = ko.utils.unwrapObservable(html); if ((html !== null) && (html !== undefined)) { if (typeof html != 'string') html = html.toString(); // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments, // for example elements which are not normally allowed to exist on their own. // If you've referenced jQuery we'll use that rather than duplicating its code. if (jQueryInstance) { jQueryInstance(node)['html'](html); } else { // ... otherwise, use KO's own parsing logic. var parsedNodes = ko.utils.parseHtmlFragment(html); for (var i = 0; i < parsedNodes.length; i++) node.appendChild(parsedNodes[i]); } } }; })(); ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment); ko.exportSymbol('utils.setHtml', ko.utils.setHtml); ko.memoization = (function () { var memos = {}; function randomMax8HexChars() { return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1); } function generateRandomId() { return randomMax8HexChars() + randomMax8HexChars(); } function findMemoNodes(rootNode, appendToArray) { if (!rootNode) return; if (rootNode.nodeType == 8) { var memoId = ko.memoization.parseMemoText(rootNode.nodeValue); if (memoId != null) appendToArray.push({ domNode: rootNode, memoId: memoId }); } else if (rootNode.nodeType == 1) { for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++) findMemoNodes(childNodes[i], appendToArray); } } return { memoize: function (callback) { if (typeof callback != "function") throw new Error("You can only pass a function to ko.memoization.memoize()"); var memoId = generateRandomId(); memos[memoId] = callback; return ""; }, unmemoize: function (memoId, callbackParams) { var callback = memos[memoId]; if (callback === undefined) throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized."); try { callback.apply(null, callbackParams || []); return true; } finally { delete memos[memoId]; } }, unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) { var memos = []; findMemoNodes(domNode, memos); for (var i = 0, j = memos.length; i < j; i++) { var node = memos[i].domNode; var combinedParams = [node]; if (extraCallbackParamsArray) ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray); ko.memoization.unmemoize(memos[i].memoId, combinedParams); node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again if (node.parentNode) node.parentNode.removeChild(node); // If possible, erase it totally (not always possible - someone else might just hold a reference to it then call unmemoizeDomNodeAndDescendants again) } }, parseMemoText: function (memoText) { var match = memoText.match(/^\[ko_memo\:(.*?)\]$/); return match ? match[1] : null; } }; })(); ko.exportSymbol('memoization', ko.memoization); ko.exportSymbol('memoization.memoize', ko.memoization.memoize); ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize); ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText); ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants); ko.extenders = { 'throttle': function(target, timeout) { // Throttling means two things: // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate target['throttleEvaluation'] = timeout; // (2) For writable targets (observables, or writable dependent observables), we throttle *writes* // so the target cannot change value synchronously or faster than a certain rate var writeTimeoutInstance = null; return ko.dependentObservable({ 'read': target, 'write': function(value) { clearTimeout(writeTimeoutInstance); writeTimeoutInstance = setTimeout(function() { target(value); }, timeout); } }); }, 'rateLimit': function(target, options) { var timeout, method, limitFunction; if (typeof options == 'number') { timeout = options; } else { timeout = options['timeout']; method = options['method']; } limitFunction = method == 'notifyWhenChangesStop' ? debounce : throttle; target.limit(function(callback) { return limitFunction(callback, timeout); }); }, 'notify': function(target, notifyWhen) { target["equalityComparer"] = notifyWhen == "always" ? null : // null equalityComparer means to always notify valuesArePrimitiveAndEqual; } }; var primitiveTypes = { 'undefined':1, 'boolean':1, 'number':1, 'string':1 }; function valuesArePrimitiveAndEqual(a, b) { var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes); return oldValueIsPrimitive ? (a === b) : false; } function throttle(callback, timeout) { var timeoutInstance; return function () { if (!timeoutInstance) { timeoutInstance = setTimeout(function() { timeoutInstance = undefined; callback(); }, timeout); } }; } function debounce(callback, timeout) { var timeoutInstance; return function () { clearTimeout(timeoutInstance); timeoutInstance = setTimeout(callback, timeout); }; } function applyExtenders(requestedExtenders) { var target = this; if (requestedExtenders) { ko.utils.objectForEach(requestedExtenders, function(key, value) { var extenderHandler = ko.extenders[key]; if (typeof extenderHandler == 'function') { target = extenderHandler(target, value) || target; } }); } return target; } ko.exportSymbol('extenders', ko.extenders); ko.subscription = function (target, callback, disposeCallback) { this.target = target; this.callback = callback; this.disposeCallback = disposeCallback; this.isDisposed = false; ko.exportProperty(this, 'dispose', this.dispose); }; ko.subscription.prototype.dispose = function () { this.isDisposed = true; this.disposeCallback(); }; ko.subscribable = function () { ko.utils.setPrototypeOfOrExtend(this, ko.subscribable['fn']); this._subscriptions = {}; } var defaultEvent = "change"; var ko_subscribable_fn = { subscribe: function (callback, callbackTarget, event) { var self = this; event = event || defaultEvent; var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback; var subscription = new ko.subscription(self, boundCallback, function () { ko.utils.arrayRemoveItem(self._subscriptions[event], subscription); if (self.afterSubscriptionRemove) self.afterSubscriptionRemove(event); }); if (self.beforeSubscriptionAdd) self.beforeSubscriptionAdd(event); if (!self._subscriptions[event]) self._subscriptions[event] = []; self._subscriptions[event].push(subscription); return subscription; }, "notifySubscribers": function (valueToNotify, event) { event = event || defaultEvent; if (this.hasSubscriptionsForEvent(event)) { try { ko.dependencyDetection.begin(); // Begin suppressing dependency detection (by setting the top frame to undefined) for (var a = this._subscriptions[event].slice(0), i = 0, subscription; subscription = a[i]; ++i) { // In case a subscription was disposed during the arrayForEach cycle, check // for isDisposed on each subscription before invoking its callback if (!subscription.isDisposed) subscription.callback(valueToNotify); } } finally { ko.dependencyDetection.end(); // End suppressing dependency detection } } }, limit: function(limitFunction) { var self = this, selfIsObservable = ko.isObservable(self), isPending, previousValue, pendingValue, beforeChange = 'beforeChange'; if (!self._origNotifySubscribers) { self._origNotifySubscribers = self["notifySubscribers"]; self["notifySubscribers"] = function(value, event) { if (!event || event === defaultEvent) { self._rateLimitedChange(value); } else if (event === beforeChange) { self._rateLimitedBeforeChange(value); } else { self._origNotifySubscribers(value, event); } }; } var finish = limitFunction(function() { // If an observable provided a reference to itself, access it to get the latest value. // This allows computed observables to delay calculating their value until needed. if (selfIsObservable && pendingValue === self) { pendingValue = self(); } isPending = false; if (self.isDifferent(previousValue, pendingValue)) { self._origNotifySubscribers(previousValue = pendingValue); } }); self._rateLimitedChange = function(value) { isPending = true; pendingValue = value; finish(); }; self._rateLimitedBeforeChange = function(value) { if (!isPending) { previousValue = value; self._origNotifySubscribers(value, beforeChange); } }; }, hasSubscriptionsForEvent: function(event) { return this._subscriptions[event] && this._subscriptions[event].length; }, getSubscriptionsCount: function () { var total = 0; ko.utils.objectForEach(this._subscriptions, function(eventName, subscriptions) { total += subscriptions.length; }); return total; }, isDifferent: function(oldValue, newValue) { return !this['equalityComparer'] || !this['equalityComparer'](oldValue, newValue); }, extend: applyExtenders }; ko.exportProperty(ko_subscribable_fn, 'subscribe', ko_subscribable_fn.subscribe); ko.exportProperty(ko_subscribable_fn, 'extend', ko_subscribable_fn.extend); ko.exportProperty(ko_subscribable_fn, 'getSubscriptionsCount', ko_subscribable_fn.getSubscriptionsCount); // For browsers that support proto assignment, we overwrite the prototype of each // observable instance. Since observables are functions, we need Function.prototype // to still be in the prototype chain. if (ko.utils.canSetPrototype) { ko.utils.setPrototypeOf(ko_subscribable_fn, Function.prototype); } ko.subscribable['fn'] = ko_subscribable_fn; ko.isSubscribable = function (instance) { return instance != null && typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function"; }; ko.exportSymbol('subscribable', ko.subscribable); ko.exportSymbol('isSubscribable', ko.isSubscribable); ko.computedContext = ko.dependencyDetection = (function () { var outerFrames = [], currentFrame, lastId = 0; // Return a unique ID that can be assigned to an observable for dependency tracking. // Theoretically, you could eventually overflow the number storage size, resulting // in duplicate IDs. But in JavaScript, the largest exact integral value is 2^53 // or 9,007,199,254,740,992. If you created 1,000,000 IDs per second, it would // take over 285 years to reach that number. // Reference http://blog.vjeux.com/2010/javascript/javascript-max_int-number-limits.html function getId() { return ++lastId; } function begin(options) { outerFrames.push(currentFrame); currentFrame = options; } function end() { currentFrame = outerFrames.pop(); } return { begin: begin, end: end, registerDependency: function (subscribable) { if (currentFrame) { if (!ko.isSubscribable(subscribable)) throw new Error("Only subscribable things can act as dependencies"); currentFrame.callback(subscribable, subscribable._id || (subscribable._id = getId())); } }, ignore: function (callback, callbackTarget, callbackArgs) { try { begin(); return callback.apply(callbackTarget, callbackArgs || []); } finally { end(); } }, getDependenciesCount: function () { if (currentFrame) return currentFrame.computed.getDependenciesCount(); }, isInitial: function() { if (currentFrame) return currentFrame.isInitial; } }; })(); ko.exportSymbol('computedContext', ko.computedContext); ko.exportSymbol('computedContext.getDependenciesCount', ko.computedContext.getDependenciesCount); ko.exportSymbol('computedContext.isInitial', ko.computedContext.isInitial); ko.exportSymbol('computedContext.isSleeping', ko.computedContext.isSleeping); ko.observable = function (initialValue) { var _latestValue = initialValue; function observable() { if (arguments.length > 0) { // Write // Ignore writes if the value hasn't changed if (observable.isDifferent(_latestValue, arguments[0])) { observable.valueWillMutate(); _latestValue = arguments[0]; if (DEBUG) observable._latestValue = _latestValue; observable.valueHasMutated(); } return this; // Permits chained assignments } else { // Read ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation return _latestValue; } } ko.subscribable.call(observable); ko.utils.setPrototypeOfOrExtend(observable, ko.observable['fn']); if (DEBUG) observable._latestValue = _latestValue; observable.peek = function() { return _latestValue }; observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); } observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); } ko.exportProperty(observable, 'peek', observable.peek); ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated); ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate); return observable; } ko.observable['fn'] = { "equalityComparer": valuesArePrimitiveAndEqual }; var protoProperty = ko.observable.protoProperty = "__ko_proto__"; ko.observable['fn'][protoProperty] = ko.observable; // Note that for browsers that don't support proto assignment, the // inheritance chain is created manually in the ko.observable constructor if (ko.utils.canSetPrototype) { ko.utils.setPrototypeOf(ko.observable['fn'], ko.subscribable['fn']); } ko.hasPrototype = function(instance, prototype) { if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false; if (instance[protoProperty] === prototype) return true; return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain }; ko.isObservable = function (instance) { return ko.hasPrototype(instance, ko.observable); } ko.isWriteableObservable = function (instance) { // Observable if ((typeof instance == "function") && instance[protoProperty] === ko.observable) return true; // Writeable dependent observable if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction)) return true; // Anything else return false; } ko.exportSymbol('observable', ko.observable); ko.exportSymbol('isObservable', ko.isObservable); ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable); ko.exportSymbol('isWritableObservable', ko.isWriteableObservable); ko.observableArray = function (initialValues) { initialValues = initialValues || []; if (typeof initialValues != 'object' || !('length' in initialValues)) throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined."); var result = ko.observable(initialValues); ko.utils.setPrototypeOfOrExtend(result, ko.observableArray['fn']); return result.extend({'trackArrayChanges':true}); }; ko.observableArray['fn'] = { 'remove': function (valueOrPredicate) { var underlyingArray = this.peek(); var removedValues = []; var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; }; for (var i = 0; i < underlyingArray.length; i++) { var value = underlyingArray[i]; if (predicate(value)) { if (removedValues.length === 0) { this.valueWillMutate(); } removedValues.push(value); underlyingArray.splice(i, 1); i--; } } if (removedValues.length) { this.valueHasMutated(); } return removedValues; }, 'removeAll': function (arrayOfValues) { // If you passed zero args, we remove everything if (arrayOfValues === undefined) { var underlyingArray = this.peek(); var allValues = underlyingArray.slice(0); this.valueWillMutate(); underlyingArray.splice(0, underlyingArray.length); this.valueHasMutated(); return allValues; } // If you passed an arg, we interpret it as an array of entries to remove if (!arrayOfValues) return []; return this['remove'](function (value) { return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0; }); }, 'destroy': function (valueOrPredicate) { var underlyingArray = this.peek(); var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; }; this.valueWillMutate(); for (var i = underlyingArray.length - 1; i >= 0; i--) { var value = underlyingArray[i]; if (predicate(value)) underlyingArray[i]["_destroy"] = true; } this.valueHasMutated(); }, 'destroyAll': function (arrayOfValues) { // If you passed zero args, we destroy everything if (arrayOfValues === undefined) return this['destroy'](function() { return true }); // If you passed an arg, we interpret it as an array of entries to destroy if (!arrayOfValues) return []; return this['destroy'](function (value) { return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0; }); }, 'indexOf': function (item) { var underlyingArray = this(); return ko.utils.arrayIndexOf(underlyingArray, item); }, 'replace': function(oldItem, newItem) { var index = this['indexOf'](oldItem); if (index >= 0) { this.valueWillMutate(); this.peek()[index] = newItem; this.valueHasMutated(); } } }; // Populate ko.observableArray.fn with read/write functions from native arrays // Important: Do not add any additional functions here that may reasonably be used to *read* data from the array // because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) { ko.observableArray['fn'][methodName] = function () { // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of // (for consistency with mutating regular observables) var underlyingArray = this.peek(); this.valueWillMutate(); this.cacheDiffForKnownOperation(underlyingArray, methodName, arguments); var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments); this.valueHasMutated(); return methodCallResult; }; }); // Populate ko.observableArray.fn with read-only functions from native arrays ko.utils.arrayForEach(["slice"], function (methodName) { ko.observableArray['fn'][methodName] = function () { var underlyingArray = this(); return underlyingArray[methodName].apply(underlyingArray, arguments); }; }); // Note that for browsers that don't support proto assignment, the // inheritance chain is created manually in the ko.observableArray constructor if (ko.utils.canSetPrototype) { ko.utils.setPrototypeOf(ko.observableArray['fn'], ko.observable['fn']); } ko.exportSymbol('observableArray', ko.observableArray); var arrayChangeEventName = 'arrayChange'; ko.extenders['trackArrayChanges'] = function(target) { // Only modify the target observable once if (target.cacheDiffForKnownOperation) { return; } var trackingChanges = false, cachedDiff = null, pendingNotifications = 0, underlyingSubscribeFunction = target.subscribe; // Intercept "subscribe" calls, and for array change events, ensure change tracking is enabled target.subscribe = target['subscribe'] = function(callback, callbackTarget, event) { if (event === arrayChangeEventName) { trackChanges(); } return underlyingSubscribeFunction.apply(this, arguments); }; function trackChanges() { // Calling 'trackChanges' multiple times is the same as calling it once if (trackingChanges) { return; } trackingChanges = true; // Intercept "notifySubscribers" to track how many times it was called. var underlyingNotifySubscribersFunction = target['notifySubscribers']; target['notifySubscribers'] = function(valueToNotify, event) { if (!event || event === defaultEvent) { ++pendingNotifications; } return underlyingNotifySubscribersFunction.apply(this, arguments); }; // Each time the array changes value, capture a clone so that on the next // change it's possible to produce a diff var previousContents = [].concat(target.peek() || []); cachedDiff = null; target.subscribe(function(currentContents) { // Make a copy of the current contents and ensure it's an array currentContents = [].concat(currentContents || []); // Compute the diff and issue notifications, but only if someone is listening if (target.hasSubscriptionsForEvent(arrayChangeEventName)) { var changes = getChanges(previousContents, currentContents); if (changes.length) { target['notifySubscribers'](changes, arrayChangeEventName); } } // Eliminate references to the old, removed items, so they can be GCed previousContents = currentContents; cachedDiff = null; pendingNotifications = 0; }); } function getChanges(previousContents, currentContents) { // We try to re-use cached diffs. // The scenarios where pendingNotifications > 1 are when using rate-limiting or the Deferred Updates // plugin, which without this check would not be compatible with arrayChange notifications. Normally, // notifications are issued immediately so we wouldn't be queueing up more than one. if (!cachedDiff || pendingNotifications > 1) { cachedDiff = ko.utils.compareArrays(previousContents, currentContents, { 'sparse': true }); } return cachedDiff; } target.cacheDiffForKnownOperation = function(rawArray, operationName, args) { // Only run if we're currently tracking changes for this observable array // and there aren't any pending deferred notifications. if (!trackingChanges || pendingNotifications) { return; } var diff = [], arrayLength = rawArray.length, argsLength = args.length, offset = 0; function pushDiff(status, value, index) { return diff[diff.length] = { 'status': status, 'value': value, 'index': index }; } switch (operationName) { case 'push': offset = arrayLength; case 'unshift': for (var index = 0; index < argsLength; index++) { pushDiff('added', args[index], offset + index); } break; case 'pop': offset = arrayLength - 1; case 'shift': if (arrayLength) { pushDiff('deleted', rawArray[offset], offset); } break; case 'splice': // Negative start index means 'from end of array'. After that we clamp to [0...arrayLength]. // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice var startIndex = Math.min(Math.max(0, args[0] < 0 ? arrayLength + args[0] : args[0]), arrayLength), endDeleteIndex = argsLength === 1 ? arrayLength : Math.min(startIndex + (args[1] || 0), arrayLength), endAddIndex = startIndex + argsLength - 2, endIndex = Math.max(endDeleteIndex, endAddIndex), additions = [], deletions = []; for (var index = startIndex, argsIndex = 2; index < endIndex; ++index, ++argsIndex) { if (index < endDeleteIndex) deletions.push(pushDiff('deleted', rawArray[index], index)); if (index < endAddIndex) additions.push(pushDiff('added', args[argsIndex], index)); } ko.utils.findMovesInArrayComparison(deletions, additions); break; default: return; } cachedDiff = diff; }; }; ko.computed = ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) { var _latestValue, _needsEvaluation = true, _isBeingEvaluated = false, _suppressDisposalUntilDisposeWhenReturnsFalse = false, _isDisposed = false, readFunction = evaluatorFunctionOrOptions, pure = false, isSleeping = false; if (readFunction && typeof readFunction == "object") { // Single-parameter syntax - everything is on this "options" param options = readFunction; readFunction = options["read"]; } else { // Multi-parameter syntax - construct the options according to the params passed options = options || {}; if (!readFunction) readFunction = options["read"]; } if (typeof readFunction != "function") throw new Error("Pass a function that returns the value of the ko.computed"); function addSubscriptionToDependency(subscribable, id) { if (!_subscriptionsToDependencies[id]) { _subscriptionsToDependencies[id] = subscribable.subscribe(evaluatePossiblyAsync); ++_dependenciesCount; } } function disposeAllSubscriptionsToDependencies() { ko.utils.objectForEach(_subscriptionsToDependencies, function (id, subscription) { subscription.dispose(); }); _subscriptionsToDependencies = {}; } function disposeComputed() { disposeAllSubscriptionsToDependencies(); _dependenciesCount = 0; _isDisposed = true; _needsEvaluation = false; } function evaluatePossiblyAsync() { var throttleEvaluationTimeout = dependentObservable['throttleEvaluation']; if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) { clearTimeout(evaluationTimeoutInstance); evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout); } else if (dependentObservable._evalRateLimited) { dependentObservable._evalRateLimited(); } else { evaluateImmediate(); } } function evaluateImmediate(suppressChangeNotification) { if (_isBeingEvaluated) { if (pure) { throw Error("A 'pure' computed must not be called recursively"); } // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation. // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387 return; } // Do not evaluate (and possibly capture new dependencies) if disposed if (_isDisposed) { return; } if (disposeWhen && disposeWhen()) { // See comment below about _suppressDisposalUntilDisposeWhenReturnsFalse if (!_suppressDisposalUntilDisposeWhenReturnsFalse) { dispose(); return; } } else { // It just did return false, so we can stop suppressing now _suppressDisposalUntilDisposeWhenReturnsFalse = false; } _isBeingEvaluated = true; // When sleeping, recalculate the value and return. if (isSleeping) { try { var dependencyTracking = {}; ko.dependencyDetection.begin({ callback: function (subscribable, id) { if (!dependencyTracking[id]) { dependencyTracking[id] = 1; ++_dependenciesCount; } }, computed: dependentObservable, isInitial: undefined }); _dependenciesCount = 0; _latestValue = readFunction.call(evaluatorFunctionTarget); } finally { ko.dependencyDetection.end(); _isBeingEvaluated = false; } } else { try { // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal). // Then, during evaluation, we cross off any that are in fact still being used. var disposalCandidates = _subscriptionsToDependencies, disposalCount = _dependenciesCount; ko.dependencyDetection.begin({ callback: function(subscribable, id) { if (!_isDisposed) { if (disposalCount && disposalCandidates[id]) { // Don't want to dispose this subscription, as it's still being used _subscriptionsToDependencies[id] = disposalCandidates[id]; ++_dependenciesCount; delete disposalCandidates[id]; --disposalCount; } else { // Brand new subscription - add it addSubscriptionToDependency(subscribable, id); } } }, computed: dependentObservable, isInitial: pure ? undefined : !_dependenciesCount // If we're evaluating when there are no previous dependencies, it must be the first time }); _subscriptionsToDependencies = {}; _dependenciesCount = 0; try { var newValue = evaluatorFunctionTarget ? readFunction.call(evaluatorFunctionTarget) : readFunction(); } finally { ko.dependencyDetection.end(); // For each subscription no longer being used, remove it from the active subscriptions list and dispose it if (disposalCount) { ko.utils.objectForEach(disposalCandidates, function(id, toDispose) { toDispose.dispose(); }); } _needsEvaluation = false; } if (dependentObservable.isDifferent(_latestValue, newValue)) { dependentObservable["notifySubscribers"](_latestValue, "beforeChange"); _latestValue = newValue; if (DEBUG) dependentObservable._latestValue = _latestValue; if (suppressChangeNotification !== true) { // Check for strict true value since setTimeout in Firefox passes a numeric value to the function dependentObservable["notifySubscribers"](_latestValue); } } } finally { _isBeingEvaluated = false; } } if (!_dependenciesCount) dispose(); } function dependentObservable() { if (arguments.length > 0) { if (typeof writeFunction === "function") { // Writing a value writeFunction.apply(evaluatorFunctionTarget, arguments); } else { throw new Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters."); } return this; // Permits chained assignments } else { // Reading the value ko.dependencyDetection.registerDependency(dependentObservable); if (_needsEvaluation) evaluateImmediate(true /* suppressChangeNotification */); return _latestValue; } } function peek() { // Peek won't re-evaluate, except to get the initial value when "deferEvaluation" is set, or while the computed is sleeping. // Those are the only times that both of these conditions will be satisfied. if (_needsEvaluation && !_dependenciesCount) evaluateImmediate(true /* suppressChangeNotification */); return _latestValue; } function isActive() { return _needsEvaluation || _dependenciesCount > 0; } // By here, "options" is always non-null var writeFunction = options["write"], disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null, disposeWhenOption = options["disposeWhen"] || options.disposeWhen, disposeWhen = disposeWhenOption, dispose = disposeComputed, _subscriptionsToDependencies = {}, _dependenciesCount = 0, evaluationTimeoutInstance = null; if (!evaluatorFunctionTarget) evaluatorFunctionTarget = options["owner"]; ko.subscribable.call(dependentObservable); ko.utils.setPrototypeOfOrExtend(dependentObservable, ko.dependentObservable['fn']); dependentObservable.peek = peek; dependentObservable.getDependenciesCount = function () { return _dependenciesCount; }; dependentObservable.hasWriteFunction = typeof options["write"] === "function"; dependentObservable.dispose = function () { dispose(); }; dependentObservable.isActive = isActive; // Replace the limit function with one that delays evaluation as well. var originalLimit = dependentObservable.limit; dependentObservable.limit = function(limitFunction) { originalLimit.call(dependentObservable, limitFunction); dependentObservable._evalRateLimited = function() { dependentObservable._rateLimitedBeforeChange(_latestValue); _needsEvaluation = true; // Mark as dirty // Pass the observable to the rate-limit code, which will access it when // it's time to do the notification. dependentObservable._rateLimitedChange(dependentObservable); } }; if (options['pure']) { pure = true; isSleeping = true; // Starts off sleeping; will awake on the first subscription dependentObservable.beforeSubscriptionAdd = function () { // If asleep, wake up the computed and evaluate to register any dependencies. if (isSleeping) { isSleeping = false; evaluateImmediate(true /* suppressChangeNotification */); } } dependentObservable.afterSubscriptionRemove = function () { if (!dependentObservable.getSubscriptionsCount()) { disposeAllSubscriptionsToDependencies(); isSleeping = _needsEvaluation = true; } } } else if (options['deferEvaluation']) { // This will force a computed with deferEvaluation to evaluate when the first subscriptions is registered. dependentObservable.beforeSubscriptionAdd = function () { peek(); delete dependentObservable.beforeSubscriptionAdd; } } ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek); ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose); ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive); ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount); // Add a "disposeWhen" callback that, on each evaluation, disposes if the node was removed without using ko.removeNode. if (disposeWhenNodeIsRemoved) { // Since this computed is associated with a DOM node, and we don't want to dispose the computed // until the DOM node is *removed* from the document (as opposed to never having been in the document), // we'll prevent disposal until "disposeWhen" first returns false. _suppressDisposalUntilDisposeWhenReturnsFalse = true; // Only watch for the node's disposal if the value really is a node. It might not be, // e.g., { disposeWhenNodeIsRemoved: true } can be used to opt into the "only dispose // after first false result" behaviour even if there's no specific node to watch. This // technique is intended for KO's internal use only and shouldn't be documented or used // by application code, as it's likely to change in a future version of KO. if (disposeWhenNodeIsRemoved.nodeType) { disposeWhen = function () { return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || (disposeWhenOption && disposeWhenOption()); }; } } // Evaluate, unless sleeping or deferEvaluation is true if (!isSleeping && !options['deferEvaluation']) evaluateImmediate(); // Attach a DOM node disposal callback so that the computed will be proactively disposed as soon as the node is // removed using ko.removeNode. But skip if isActive is false (there will never be any dependencies to dispose). if (disposeWhenNodeIsRemoved && isActive() && disposeWhenNodeIsRemoved.nodeType) { dispose = function() { ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, dispose); disposeComputed(); }; ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose); } return dependentObservable; }; ko.isComputed = function(instance) { return ko.hasPrototype(instance, ko.dependentObservable); }; var protoProp = ko.observable.protoProperty; // == "__ko_proto__" ko.dependentObservable[protoProp] = ko.observable; ko.dependentObservable['fn'] = { "equalityComparer": valuesArePrimitiveAndEqual }; ko.dependentObservable['fn'][protoProp] = ko.dependentObservable; // Note that for browsers that don't support proto assignment, the // inheritance chain is created manually in the ko.dependentObservable constructor if (ko.utils.canSetPrototype) { ko.utils.setPrototypeOf(ko.dependentObservable['fn'], ko.subscribable['fn']); } ko.exportSymbol('dependentObservable', ko.dependentObservable); ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable" ko.exportSymbol('isComputed', ko.isComputed); ko.pureComputed = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget) { if (typeof evaluatorFunctionOrOptions === 'function') { return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget, {'pure':true}); } else { evaluatorFunctionOrOptions = ko.utils.extend({}, evaluatorFunctionOrOptions); // make a copy of the parameter object evaluatorFunctionOrOptions['pure'] = true; return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget); } } ko.exportSymbol('pureComputed', ko.pureComputed); (function() { var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle) ko.toJS = function(rootObject) { if (arguments.length == 0) throw new Error("When calling ko.toJS, pass the object you want to convert."); // We just unwrap everything at every level in the object graph return mapJsObjectGraph(rootObject, function(valueToMap) { // Loop because an observable's value might in turn be another observable wrapper for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++) valueToMap = valueToMap(); return valueToMap; }); }; ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional var plainJavaScriptObject = ko.toJS(rootObject); return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space); }; function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) { visitedObjects = visitedObjects || new objectLookup(); rootObject = mapInputCallback(rootObject); var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date)) && (!(rootObject instanceof String)) && (!(rootObject instanceof Number)) && (!(rootObject instanceof Boolean)); if (!canHaveProperties) return rootObject; var outputProperties = rootObject instanceof Array ? [] : {}; visitedObjects.save(rootObject, outputProperties); visitPropertiesOrArrayEntries(rootObject, function(indexer) { var propertyValue = mapInputCallback(rootObject[indexer]); switch (typeof propertyValue) { case "boolean": case "number": case "string": case "function": outputProperties[indexer] = propertyValue; break; case "object": case "undefined": var previouslyMappedValue = visitedObjects.get(propertyValue); outputProperties[indexer] = (previouslyMappedValue !== undefined) ? previouslyMappedValue : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects); break; } }); return outputProperties; } function visitPropertiesOrArrayEntries(rootObject, visitorCallback) { if (rootObject instanceof Array) { for (var i = 0; i < rootObject.length; i++) visitorCallback(i); // For arrays, also respect toJSON property for custom mappings (fixes #278) if (typeof rootObject['toJSON'] == 'function') visitorCallback('toJSON'); } else { for (var propertyName in rootObject) { visitorCallback(propertyName); } } }; function objectLookup() { this.keys = []; this.values = []; }; objectLookup.prototype = { constructor: objectLookup, save: function(key, value) { var existingIndex = ko.utils.arrayIndexOf(this.keys, key); if (existingIndex >= 0) this.values[existingIndex] = value; else { this.keys.push(key); this.values.push(value); } }, get: function(key) { var existingIndex = ko.utils.arrayIndexOf(this.keys, key); return (existingIndex >= 0) ? this.values[existingIndex] : undefined; } }; })(); ko.exportSymbol('toJS', ko.toJS); ko.exportSymbol('toJSON', ko.toJSON); (function () { var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__'; // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns. ko.selectExtensions = { readValue : function(element) { switch (ko.utils.tagNameLower(element)) { case 'option': if (element[hasDomDataExpandoProperty] === true) return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey); return ko.utils.ieVersion <= 7 ? (element.getAttributeNode('value') && element.getAttributeNode('value').specified ? element.value : element.text) : element.value; case 'select': return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined; default: return element.value; } }, writeValue: function(element, value, allowUnset) { switch (ko.utils.tagNameLower(element)) { case 'option': switch(typeof value) { case "string": ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined); if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node delete element[hasDomDataExpandoProperty]; } element.value = value; break; default: // Store arbitrary object using DomData ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value); element[hasDomDataExpandoProperty] = true; // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value. element.value = typeof value === "number" ? value : ""; break; } break; case 'select': if (value === "" || value === null) // A blank string or null value will select the caption value = undefined; var selection = -1; for (var i = 0, n = element.options.length, optionValue; i < n; ++i) { optionValue = ko.selectExtensions.readValue(element.options[i]); // Include special check to handle selecting a caption with a blank string value if (optionValue == value || (optionValue == "" && value === undefined)) { selection = i; break; } } if (allowUnset || selection >= 0 || (value === undefined && element.size > 1)) { element.selectedIndex = selection; } break; default: if ((value === null) || (value === undefined)) value = ""; element.value = value; break; } } }; })(); ko.exportSymbol('selectExtensions', ko.selectExtensions); ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue); ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue); ko.expressionRewriting = (function () { var javaScriptReservedWords = ["true", "false", "null", "undefined"]; // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c). // This also will not properly handle nested brackets (e.g., obj1[obj2['prop']]; see #911). var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i; function getWriteableValue(expression) { if (ko.utils.arrayIndexOf(javaScriptReservedWords, expression) >= 0) return false; var match = expression.match(javaScriptAssignmentTarget); return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression; } // The following regular expressions will be used to split an object-literal string into tokens // These two match strings, either with double quotes or single quotes var stringDouble = '"(?:[^"\\\\]|\\\\.)*"', stringSingle = "'(?:[^'\\\\]|\\\\.)*'", // Matches a regular expression (text enclosed by slashes), but will also match sets of divisions // as a regular expression (this is handled by the parsing loop below). stringRegexp = '/(?:[^/\\\\]|\\\\.)*/\w*', // These characters have special meaning to the parser and must not appear in the middle of a // token, except as part of a string. specials = ',"\'{}()/:[\\]', // Match text (at least two characters) that does not contain any of the above special characters, // although some of the special characters are allowed to start it (all but the colon and comma). // The text can contain spaces, but leading or trailing spaces are skipped. everyThingElse = '[^\\s:,/][^' + specials + ']*[^\\s' + specials + ']', // Match any non-space character not matched already. This will match colons and commas, since they're // not matched by "everyThingElse", but will also match any other single character that wasn't already // matched (for example: in "a: 1, b: 2", each of the non-space characters will be matched by oneNotSpace). oneNotSpace = '[^\\s]', // Create the actual regular expression by or-ing the above strings. The order is important. bindingToken = RegExp(stringDouble + '|' + stringSingle + '|' + stringRegexp + '|' + everyThingElse + '|' + oneNotSpace, 'g'), // Match end of previous token to determine whether a slash is a division or regex. divisionLookBehind = /[\])"'A-Za-z0-9_$]+$/, keywordRegexLookBehind = {'in':1,'return':1,'typeof':1}; function parseObjectLiteral(objectLiteralString) { // Trim leading and trailing spaces from the string var str = ko.utils.stringTrim(objectLiteralString); // Trim braces '{' surrounding the whole object literal if (str.charCodeAt(0) === 123) str = str.slice(1, -1); // Split into tokens var result = [], toks = str.match(bindingToken), key, values, depth = 0; if (toks) { // Append a comma so that we don't need a separate code block to deal with the last item toks.push(','); for (var i = 0, tok; tok = toks[i]; ++i) { var c = tok.charCodeAt(0); // A comma signals the end of a key/value pair if depth is zero if (c === 44) { // "," if (depth <= 0) { if (key) result.push(values ? {key: key, value: values.join('')} : {'unknown': key}); key = values = depth = 0; continue; } // Simply skip the colon that separates the name and value } else if (c === 58) { // ":" if (!values) continue; // A set of slashes is initially matched as a regular expression, but could be division } else if (c === 47 && i && tok.length > 1) { // "/" // Look at the end of the previous token to determine if the slash is actually division var match = toks[i-1].match(divisionLookBehind); if (match && !keywordRegexLookBehind[match[0]]) { // The slash is actually a division punctuator; re-parse the remainder of the string (not including the slash) str = str.substr(str.indexOf(tok) + 1); toks = str.match(bindingToken); toks.push(','); i = -1; // Continue with just the slash tok = '/'; } // Increment depth for parentheses, braces, and brackets so that interior commas are ignored } else if (c === 40 || c === 123 || c === 91) { // '(', '{', '[' ++depth; } else if (c === 41 || c === 125 || c === 93) { // ')', '}', ']' --depth; // The key must be a single token; if it's a string, trim the quotes } else if (!key && !values) { key = (c === 34 || c === 39) /* '"', "'" */ ? tok.slice(1, -1) : tok; continue; } if (values) values.push(tok); else values = [tok]; } } return result; } // Two-way bindings include a write function that allow the handler to update the value even if it's not an observable. var twoWayBindings = {}; function preProcessBindings(bindingsStringOrKeyValueArray, bindingOptions) { bindingOptions = bindingOptions || {}; function processKeyValue(key, val) { var writableVal; function callPreprocessHook(obj) { return (obj && obj['preprocess']) ? (val = obj['preprocess'](val, key, processKeyValue)) : true; } if (!bindingParams) { if (!callPreprocessHook(ko['getBindingHandler'](key))) return; if (twoWayBindings[key] && (writableVal = getWriteableValue(val))) { // For two-way bindings, provide a write method in case the value // isn't a writable observable. propertyAccessorResultStrings.push("'" + key + "':function(_z){" + writableVal + "=_z}"); } } // Values are wrapped in a function so that each value can be accessed independently if (makeValueAccessors) { val = 'function(){return ' + val + ' }'; } resultStrings.push("'" + key + "':" + val); } var resultStrings = [], propertyAccessorResultStrings = [], makeValueAccessors = bindingOptions['valueAccessors'], bindingParams = bindingOptions['bindingParams'], keyValueArray = typeof bindingsStringOrKeyValueArray === "string" ? parseObjectLiteral(bindingsStringOrKeyValueArray) : bindingsStringOrKeyValueArray; ko.utils.arrayForEach(keyValueArray, function(keyValue) { processKeyValue(keyValue.key || keyValue['unknown'], keyValue.value); }); if (propertyAccessorResultStrings.length) processKeyValue('_ko_property_writers', "{" + propertyAccessorResultStrings.join(",") + " }"); return resultStrings.join(","); } return { bindingRewriteValidators: [], twoWayBindings: twoWayBindings, parseObjectLiteral: parseObjectLiteral, preProcessBindings: preProcessBindings, keyValueArrayContainsKey: function(keyValueArray, key) { for (var i = 0; i < keyValueArray.length; i++) if (keyValueArray[i]['key'] == key) return true; return false; }, // Internal, private KO utility for updating model properties from within bindings // property: If the property being updated is (or might be) an observable, pass it here // If it turns out to be a writable observable, it will be written to directly // allBindings: An object with a get method to retrieve bindings in the current execution context. // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus' // value: The value to be written // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if // it is !== existing value on that writable observable writeValueToProperty: function(property, allBindings, key, value, checkIfDifferent) { if (!property || !ko.isObservable(property)) { var propWriters = allBindings.get('_ko_property_writers'); if (propWriters && propWriters[key]) propWriters[key](value); } else if (ko.isWriteableObservable(property) && (!checkIfDifferent || property.peek() !== value)) { property(value); } } }; })(); ko.exportSymbol('expressionRewriting', ko.expressionRewriting); ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators); ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral); ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings); // Making bindings explicitly declare themselves as "two way" isn't ideal in the long term (it would be better if // all bindings could use an official 'property writer' API without needing to declare that they might). However, // since this is not, and has never been, a public API (_ko_property_writers was never documented), it's acceptable // as an internal implementation detail in the short term. // For those developers who rely on _ko_property_writers in their custom bindings, we expose _twoWayBindings as an // undocumented feature that makes it relatively easy to upgrade to KO 3.0. However, this is still not an official // public API, and we reserve the right to remove it at any time if we create a real public property writers API. ko.exportSymbol('expressionRewriting._twoWayBindings', ko.expressionRewriting.twoWayBindings); // For backward compatibility, define the following aliases. (Previously, these function names were misleading because // they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.) ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting); ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings); (function() { // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes // may be used to represent hierarchy (in addition to the DOM's natural hierarchy). // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state // of that virtual hierarchy // // The point of all this is to support containerless templates (e.g., blah) // without having to scatter special cases all over the binding and templating code. // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186) // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property. // So, use node.text where available, and node.nodeValue elsewhere var commentNodesHaveTextProperty = document && document.createComment("test").text === ""; var startCommentRegex = commentNodesHaveTextProperty ? /^$/ : /^\s*ko(?:\s+([\s\S]+))?\s*$/; var endCommentRegex = commentNodesHaveTextProperty ? /^$/ : /^\s*\/ko\s*$/; var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true }; function isStartComment(node) { return (node.nodeType == 8) && startCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue); } function isEndComment(node) { return (node.nodeType == 8) && endCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue); } function getVirtualChildren(startComment, allowUnbalanced) { var currentNode = startComment; var depth = 1; var children = []; while (currentNode = currentNode.nextSibling) { if (isEndComment(currentNode)) { depth--; if (depth === 0) return children; } children.push(currentNode); if (isStartComment(currentNode)) depth++; } if (!allowUnbalanced) throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue); return null; } function getMatchingEndComment(startComment, allowUnbalanced) { var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced); if (allVirtualChildren) { if (allVirtualChildren.length > 0) return allVirtualChildren[allVirtualChildren.length - 1].nextSibling; return startComment.nextSibling; } else return null; // Must have no matching end comment, and allowUnbalanced is true } function getUnbalancedChildTags(node) { // e.g., from
OK
Another, returns: Another // from
OK
, returns: var childNode = node.firstChild, captureRemaining = null; if (childNode) { do { if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes captureRemaining.push(childNode); else if (isStartComment(childNode)) { var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true); if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set childNode = matchingEndComment; else captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point } else if (isEndComment(childNode)) { captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing } } while (childNode = childNode.nextSibling); } return captureRemaining; } ko.virtualElements = { allowedBindings: {}, childNodes: function(node) { return isStartComment(node) ? getVirtualChildren(node) : node.childNodes; }, emptyNode: function(node) { if (!isStartComment(node)) ko.utils.emptyDomNode(node); else { var virtualChildren = ko.virtualElements.childNodes(node); for (var i = 0, j = virtualChildren.length; i < j; i++) ko.removeNode(virtualChildren[i]); } }, setDomNodeChildren: function(node, childNodes) { if (!isStartComment(node)) ko.utils.setDomNodeChildren(node, childNodes); else { ko.virtualElements.emptyNode(node); var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children for (var i = 0, j = childNodes.length; i < j; i++) endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode); } }, prepend: function(containerNode, nodeToPrepend) { if (!isStartComment(containerNode)) { if (containerNode.firstChild) containerNode.insertBefore(nodeToPrepend, containerNode.firstChild); else containerNode.appendChild(nodeToPrepend); } else { // Start comments must always have a parent and at least one following sibling (the end comment) containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling); } }, insertAfter: function(containerNode, nodeToInsert, insertAfterNode) { if (!insertAfterNode) { ko.virtualElements.prepend(containerNode, nodeToInsert); } else if (!isStartComment(containerNode)) { // Insert after insertion point if (insertAfterNode.nextSibling) containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling); else containerNode.appendChild(nodeToInsert); } else { // Children of start comments must always have a parent and at least one following sibling (the end comment) containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling); } }, firstChild: function(node) { if (!isStartComment(node)) return node.firstChild; if (!node.nextSibling || isEndComment(node.nextSibling)) return null; return node.nextSibling; }, nextSibling: function(node) { if (isStartComment(node)) node = getMatchingEndComment(node); if (node.nextSibling && isEndComment(node.nextSibling)) return null; return node.nextSibling; }, hasBindingValue: isStartComment, virtualNodeBindingValue: function(node) { var regexMatch = (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex); return regexMatch ? regexMatch[1] : null; }, normaliseVirtualElementDomStructure: function(elementVerified) { // Workaround for https://github.com/SteveSanderson/knockout/issues/155 // (IE <= 8 or IE 9 quirks mode parses your HTML weirdly, treating closing tags as if they don't exist, thereby moving comment nodes // that are direct descendants of
    into the preceding
  • ) if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)]) return; // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags // must be intended to appear *after* that child, so move them there. var childNode = elementVerified.firstChild; if (childNode) { do { if (childNode.nodeType === 1) { var unbalancedTags = getUnbalancedChildTags(childNode); if (unbalancedTags) { // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child var nodeToInsertBefore = childNode.nextSibling; for (var i = 0; i < unbalancedTags.length; i++) { if (nodeToInsertBefore) elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore); else elementVerified.appendChild(unbalancedTags[i]); } } } } while (childNode = childNode.nextSibling); } } }; })(); ko.exportSymbol('virtualElements', ko.virtualElements); ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings); ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode); //ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter); //ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend); ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren); (function() { var defaultBindingAttributeName = "data-bind"; ko.bindingProvider = function() { this.bindingCache = {}; }; ko.utils.extend(ko.bindingProvider.prototype, { 'nodeHasBindings': function(node) { switch (node.nodeType) { case 1: // Element return node.getAttribute(defaultBindingAttributeName) != null || ko.components['getComponentNameForNode'](node); case 8: // Comment node return ko.virtualElements.hasBindingValue(node); default: return false; } }, 'getBindings': function(node, bindingContext) { var bindingsString = this['getBindingsString'](node, bindingContext), parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null; return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ false); }, 'getBindingAccessors': function(node, bindingContext) { var bindingsString = this['getBindingsString'](node, bindingContext), parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node, { 'valueAccessors': true }) : null; return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ true); }, // The following function is only used internally by this default provider. // It's not part of the interface definition for a general binding provider. 'getBindingsString': function(node, bindingContext) { switch (node.nodeType) { case 1: return node.getAttribute(defaultBindingAttributeName); // Element case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node default: return null; } }, // The following function is only used internally by this default provider. // It's not part of the interface definition for a general binding provider. 'parseBindingsString': function(bindingsString, bindingContext, node, options) { try { var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache, options); return bindingFunction(bindingContext, node); } catch (ex) { ex.message = "Unable to parse bindings.\nBindings value: " + bindingsString + "\nMessage: " + ex.message; throw ex; } } }); ko.bindingProvider['instance'] = new ko.bindingProvider(); function createBindingsStringEvaluatorViaCache(bindingsString, cache, options) { var cacheKey = bindingsString + (options && options['valueAccessors'] || ''); return cache[cacheKey] || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString, options)); } function createBindingsStringEvaluator(bindingsString, options) { // Build the source for a function that evaluates "expression" // For each scope variable, add an extra level of "with" nesting // Example result: with(sc1) { with(sc0) { return (expression) } } var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString, options), functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}"; return new Function("$context", "$element", functionBody); } })(); ko.exportSymbol('bindingProvider', ko.bindingProvider); (function () { ko.bindingHandlers = {}; // The following element types will not be recursed into during binding. In the future, we // may consider adding