ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
+468
View File
@@ -0,0 +1,468 @@
/*!
* Knockout ES5 plugin - https://github.com/SteveSanderson/knockout-es5
* Copyright (c) Steve Sanderson
* MIT license
*/
(function(global, undefined) {
'use strict';
var ko;
// Model tracking
// --------------
//
// This is the central feature of Knockout-ES5. We augment model objects by converting properties
// into ES5 getter/setter pairs that read/write an underlying Knockout observable. This means you can
// use plain JavaScript syntax to read/write the property while still getting the full benefits of
// Knockout's automatic dependency detection and notification triggering.
//
// For comparison, here's Knockout ES3-compatible syntax:
//
// var firstNameLength = myModel.user().firstName().length; // Read
// myModel.user().firstName('Bert'); // Write
//
// ... versus Knockout-ES5 syntax:
//
// var firstNameLength = myModel.user.firstName.length; // Read
// myModel.user.firstName = 'Bert'; // Write
// `ko.track(model)` converts each property on the given model object into a getter/setter pair that
// wraps a Knockout observable. Optionally specify an array of property names to wrap; otherwise we
// wrap all properties. If any of the properties are already observables, we replace them with
// ES5 getter/setter pairs that wrap your original observable instances. In the case of readonly
// ko.computed properties, we simply do not define a setter (so attempted writes will be ignored,
// which is how ES5 readonly properties normally behave).
//
// By design, this does *not* recursively walk child object properties, because making literally
// everything everywhere independently observable is usually unhelpful. When you do want to track
// child object properties independently, define your own class for those child objects and put
// a separate ko.track call into its constructor --- this gives you far more control.
/**
* @param {object} obj
* @param {object|array.<string>} propertyNamesOrSettings
* @param {boolean} propertyNamesOrSettings.deep Use deep track.
* @param {array.<string>} propertyNamesOrSettings.fields Array of property names to wrap.
* todo: @param {array.<string>} propertyNamesOrSettings.exclude Array of exclude property names to wrap.
* todo: @param {function(string, *):boolean} propertyNamesOrSettings.filter Function to filter property
* names to wrap. A function that takes ... params
* @return {object}
*/
function track(obj, propertyNamesOrSettings) {
if (!obj || typeof obj !== 'object') {
throw new Error('When calling ko.track, you must pass an object as the first parameter.');
}
var propertyNames;
if ( isPlainObject(propertyNamesOrSettings) ) {
// defaults
propertyNamesOrSettings.deep = propertyNamesOrSettings.deep || false;
propertyNamesOrSettings.fields = propertyNamesOrSettings.fields || Object.getOwnPropertyNames(obj);
propertyNamesOrSettings.lazy = propertyNamesOrSettings.lazy || false;
wrap(obj, propertyNamesOrSettings.fields, propertyNamesOrSettings);
} else {
propertyNames = propertyNamesOrSettings || Object.getOwnPropertyNames(obj);
wrap(obj, propertyNames, {});
}
return obj;
}
// fix for ie
var rFunctionName = /^function\s*([^\s(]+)/;
function getFunctionName( ctor ){
if (ctor.name) {
return ctor.name;
}
return (ctor.toString().trim().match( rFunctionName ) || [])[1];
}
function canTrack(obj) {
return obj && typeof obj === 'object' && getFunctionName(obj.constructor) === 'Object';
}
function createPropertyDescriptor(originalValue, prop, map) {
var isObservable = ko.isObservable(originalValue);
var isArray = !isObservable && Array.isArray(originalValue);
var observable = isObservable ? originalValue
: isArray ? ko.observableArray(originalValue)
: ko.observable(originalValue);
map[prop] = function () { return observable; };
// add check in case the object is already an observable array
if (isArray || (isObservable && 'push' in observable)) {
notifyWhenPresentOrFutureArrayValuesMutate(ko, observable);
}
return {
configurable: true,
enumerable: true,
get: observable,
set: ko.isWriteableObservable(observable) ? observable : undefined
};
}
function createLazyPropertyDescriptor(originalValue, prop, map) {
if (ko.isObservable(originalValue)) {
// no need to be lazy if we already have an observable
return createPropertyDescriptor(originalValue, prop, map);
}
var observable;
function getOrCreateObservable(value, writing) {
if (observable) {
return writing ? observable(value) : observable;
}
if (Array.isArray(value)) {
observable = ko.observableArray(value);
notifyWhenPresentOrFutureArrayValuesMutate(ko, observable);
return observable;
}
return (observable = ko.observable(value));
}
map[prop] = function () { return getOrCreateObservable(originalValue); };
return {
configurable: true,
enumerable: true,
get: function () { return getOrCreateObservable(originalValue)(); },
set: function (value) { getOrCreateObservable(value, true); }
};
}
function wrap(obj, props, options) {
if (!props.length) {
return;
}
var allObservablesForObject = getAllObservablesForObject(obj, true);
var descriptors = {};
props.forEach(function (prop) {
// Skip properties that are already tracked
if (prop in allObservablesForObject) {
return;
}
// Skip properties where descriptor can't be redefined
if (Object.getOwnPropertyDescriptor(obj, prop).configurable === false){
return;
}
var originalValue = obj[prop];
descriptors[prop] = (options.lazy ? createLazyPropertyDescriptor : createPropertyDescriptor)
(originalValue, prop, allObservablesForObject);
if (options.deep && canTrack(originalValue)) {
wrap(originalValue, Object.keys(originalValue), options);
}
});
Object.defineProperties(obj, descriptors);
}
function isPlainObject( obj ){
return !!obj && typeof obj === 'object' && obj.constructor === Object;
}
// Lazily created by `getAllObservablesForObject` below. Has to be created lazily because the
// WeakMap factory isn't available until the module has finished loading (may be async).
var objectToObservableMap;
// Gets or creates the hidden internal key-value collection of observables corresponding to
// properties on the model object.
function getAllObservablesForObject(obj, createIfNotDefined) {
if (!objectToObservableMap) {
objectToObservableMap = weakMapFactory();
}
var result = objectToObservableMap.get(obj);
if (!result && createIfNotDefined) {
result = {};
objectToObservableMap.set(obj, result);
}
return result;
}
// Removes the internal references to observables mapped to the specified properties
// or the entire object reference if no properties are passed in. This allows the
// observables to be replaced and tracked again.
function untrack(obj, propertyNames) {
if (!objectToObservableMap) {
return;
}
if (arguments.length === 1) {
objectToObservableMap['delete'](obj);
} else {
var allObservablesForObject = getAllObservablesForObject(obj, false);
if (allObservablesForObject) {
propertyNames.forEach(function(propertyName) {
delete allObservablesForObject[propertyName];
});
}
}
}
// Computed properties
// -------------------
//
// The preceding code is already sufficient to upgrade ko.computed model properties to ES5
// getter/setter pairs (or in the case of readonly ko.computed properties, just a getter).
// These then behave like a regular property with a getter function, except they are smarter:
// your evaluator is only invoked when one of its dependencies changes. The result is cached
// and used for all evaluations until the next time a dependency changes).
//
// However, instead of forcing developers to declare a ko.computed property explicitly, it's
// nice to offer a utility function that declares a computed getter directly.
// Implements `ko.defineProperty`
function defineComputedProperty(obj, propertyName, evaluatorOrOptions) {
var ko = this,
computedOptions = { owner: obj, deferEvaluation: true };
if (typeof evaluatorOrOptions === 'function') {
computedOptions.read = evaluatorOrOptions;
} else {
if ('value' in evaluatorOrOptions) {
throw new Error('For ko.defineProperty, you must not specify a "value" for the property. ' +
'You must provide a "get" function.');
}
if (typeof evaluatorOrOptions.get !== 'function') {
throw new Error('For ko.defineProperty, the third parameter must be either an evaluator function, ' +
'or an options object containing a function called "get".');
}
computedOptions.read = evaluatorOrOptions.get;
computedOptions.write = evaluatorOrOptions.set;
}
obj[propertyName] = ko.computed(computedOptions);
track.call(ko, obj, [propertyName]);
return obj;
}
// Array handling
// --------------
//
// Arrays are special, because unlike other property types, they have standard mutator functions
// (`push`/`pop`/`splice`/etc.) and it's desirable to trigger a change notification whenever one of
// those mutator functions is invoked.
//
// Traditionally, Knockout handles this by putting special versions of `push`/`pop`/etc. on observable
// arrays that mutate the underlying array and then trigger a notification. That approach doesn't
// work for Knockout-ES5 because properties now return the underlying arrays, so the mutator runs
// in the context of the underlying array, not any particular observable:
//
// // Operates on the underlying array value
// myModel.someCollection.push('New value');
//
// To solve this, Knockout-ES5 detects array values, and modifies them as follows:
// 1. Associates a hidden subscribable with each array instance that it encounters
// 2. Intercepts standard mutators (`push`/`pop`/etc.) and makes them trigger the subscribable
// Then, for model properties whose values are arrays, the property's underlying observable
// subscribes to the array subscribable, so it can trigger a change notification after mutation.
// Given an observable that underlies a model property, watch for any array value that might
// be assigned as the property value, and hook into its change events
function notifyWhenPresentOrFutureArrayValuesMutate(ko, observable) {
var watchingArraySubscription = null;
ko.computed(function () {
// Unsubscribe to any earlier array instance
if (watchingArraySubscription) {
watchingArraySubscription.dispose();
watchingArraySubscription = null;
}
// Subscribe to the new array instance
var newArrayInstance = observable();
if (newArrayInstance instanceof Array) {
watchingArraySubscription = startWatchingArrayInstance(ko, observable, newArrayInstance);
}
});
}
// Listens for array mutations, and when they happen, cause the observable to fire notifications.
// This is used to make model properties of type array fire notifications when the array changes.
// Returns a subscribable that can later be disposed.
function startWatchingArrayInstance(ko, observable, arrayInstance) {
var subscribable = getSubscribableForArray(ko, arrayInstance);
return subscribable.subscribe(observable);
}
// Lazily created by `getSubscribableForArray` below. Has to be created lazily because the
// WeakMap factory isn't available until the module has finished loading (may be async).
var arraySubscribablesMap;
// Gets or creates a subscribable that fires after each array mutation
function getSubscribableForArray(ko, arrayInstance) {
if (!arraySubscribablesMap) {
arraySubscribablesMap = weakMapFactory();
}
var subscribable = arraySubscribablesMap.get(arrayInstance);
if (!subscribable) {
subscribable = new ko.subscribable();
arraySubscribablesMap.set(arrayInstance, subscribable);
var notificationPauseSignal = {};
wrapStandardArrayMutators(arrayInstance, subscribable, notificationPauseSignal);
addKnockoutArrayMutators(ko, arrayInstance, subscribable, notificationPauseSignal);
}
return subscribable;
}
// After each array mutation, fires a notification on the given subscribable
function wrapStandardArrayMutators(arrayInstance, subscribable, notificationPauseSignal) {
['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'].forEach(function(fnName) {
var origMutator = arrayInstance[fnName];
arrayInstance[fnName] = function() {
var result = origMutator.apply(this, arguments);
if (notificationPauseSignal.pause !== true) {
subscribable.notifySubscribers(this);
}
return result;
};
});
}
// Adds Knockout's additional array mutation functions to the array
function addKnockoutArrayMutators(ko, arrayInstance, subscribable, notificationPauseSignal) {
['remove', 'removeAll', 'destroy', 'destroyAll', 'replace'].forEach(function(fnName) {
// Make it a non-enumerable property for consistency with standard Array functions
Object.defineProperty(arrayInstance, fnName, {
enumerable: false,
value: function() {
var result;
// These additional array mutators are built using the underlying push/pop/etc.
// mutators, which are wrapped to trigger notifications. But we don't want to
// trigger multiple notifications, so pause the push/pop/etc. wrappers and
// delivery only one notification at the end of the process.
notificationPauseSignal.pause = true;
try {
// Creates a temporary observableArray that can perform the operation.
result = ko.observableArray.fn[fnName].apply(ko.observableArray(arrayInstance), arguments);
}
finally {
notificationPauseSignal.pause = false;
}
subscribable.notifySubscribers(arrayInstance);
return result;
}
});
});
}
// Static utility functions
// ------------------------
//
// Since Knockout-ES5 sets up properties that return values, not observables, you can't
// trivially subscribe to the underlying observables (e.g., `someProperty.subscribe(...)`),
// or tell them that object values have mutated, etc. To handle this, we set up some
// extra utility functions that can return or work with the underlying observables.
// Returns the underlying observable associated with a model property (or `null` if the
// model or property doesn't exist, or isn't associated with an observable). This means
// you can subscribe to the property, e.g.:
//
// ko.getObservable(model, 'propertyName')
// .subscribe(function(newValue) { ... });
function getObservable(obj, propertyName) {
if (!obj || typeof obj !== 'object') {
return null;
}
var allObservablesForObject = getAllObservablesForObject(obj, false);
if (allObservablesForObject && propertyName in allObservablesForObject) {
return allObservablesForObject[propertyName]();
}
return null;
}
// Returns a boolean indicating whether the property on the object has an underlying
// observables. This does the check in a way not to create an observable if the
// object was created with lazily created observables
function isTracked(obj, propertyName) {
if (!obj || typeof obj !== 'object') {
return false;
}
var allObservablesForObject = getAllObservablesForObject(obj, false);
return !!allObservablesForObject && propertyName in allObservablesForObject;
}
// Causes a property's associated observable to fire a change notification. Useful when
// the property value is a complex object and you've modified a child property.
function valueHasMutated(obj, propertyName) {
var observable = getObservable(obj, propertyName);
if (observable) {
observable.valueHasMutated();
}
}
// Module initialisation
// ---------------------
//
// When this script is first evaluated, it works out what kind of module loading scenario
// it is in (Node.js or a browser `<script>` tag), stashes a reference to its dependencies
// (currently that's just the WeakMap shim), and then finally attaches itself to whichever
// instance of Knockout.js it can find.
// A function that returns a new ES6-compatible WeakMap instance (using ES5 shim if needed).
// Instantiated by prepareExports, accounting for which module loader is being used.
var weakMapFactory;
// Extends a Knockout instance with Knockout-ES5 functionality
function attachToKo(ko) {
ko.track = track;
ko.untrack = untrack;
ko.getObservable = getObservable;
ko.valueHasMutated = valueHasMutated;
ko.defineProperty = defineComputedProperty;
// todo: test it, maybe added it to ko. directly
ko.es5 = {
getAllObservablesForObject: getAllObservablesForObject,
notifyWhenPresentOrFutureArrayValuesMutate: notifyWhenPresentOrFutureArrayValuesMutate,
isTracked: isTracked
};
}
// Determines which module loading scenario we're in, grabs dependencies, and attaches to KO
function prepareExports() {
if (typeof exports === 'object' && typeof module === 'object') {
// Node.js case - load KO and WeakMap modules synchronously
ko = require('knockout');
var WM = require('../lib/weakmap');
attachToKo(ko);
weakMapFactory = function() { return new WM(); };
module.exports = ko;
} else if (typeof define === 'function' && define.amd) {
define(['knockout'], function(koModule) {
ko = koModule;
attachToKo(koModule);
weakMapFactory = function() { return new global.WeakMap(); };
return koModule;
});
} else if ('ko' in global) {
// Non-module case - attach to the global instance, and assume a global WeakMap constructor
ko = global.ko;
attachToKo(global.ko);
weakMapFactory = function() { return new global.WeakMap(); };
}
}
prepareExports();
})(this);
+331
View File
@@ -0,0 +1,331 @@
/*!
Knockout Fast Foreach v0.4.1 (2015-07-17T14:06:15.974Z)
By: Brian M Hunt (C) 2015
License: MIT
Adds `fastForEach` to `ko.bindingHandlers`.
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['knockout'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('knockout'));
} else {
root.KnockoutFastForeach = factory(root.ko);
}
}(this, function (ko) {
"use strict";
// index.js
// --------
// Fast For Each
//
// Employing sound techniques to make a faster Knockout foreach binding.
// --------
// Utilities
// from https://github.com/jonschlinkert/is-plain-object
function isPlainObject(o) {
return !!o && typeof o === 'object' && o.constructor === Object;
}
// From knockout/src/virtualElements.js
var commentNodesHaveTextProperty = document && document.createComment("test").text === "<!--test-->";
var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+([\s\S]+))?\s*-->$/ : /^\s*ko(?:\s+([\s\S]+))?\s*$/;
var supportsDocumentFragment = document && typeof document.createDocumentFragment === "function";
function isVirtualNode(node) {
return (node.nodeType === 8) && startCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
}
// Get a copy of the (possibly virtual) child nodes of the given element,
// put them into a container, then empty the given node.
function makeTemplateNode(sourceNode) {
var container = document.createElement("div");
var parentNode;
if (sourceNode.content) {
// For e.g. <template> tags
parentNode = sourceNode.content;
} else if (sourceNode.tagName === 'SCRIPT') {
parentNode = document.createElement("div");
parentNode.innerHTML = sourceNode.text;
} else {
// Anything else e.g. <div>
parentNode = sourceNode;
}
ko.utils.arrayForEach(ko.virtualElements.childNodes(parentNode), function (child) {
// FIXME - This cloneNode could be expensive; we may prefer to iterate over the
// parentNode children in reverse (so as not to foul the indexes as childNodes are
// removed from parentNode when inserted into the container)
if (child) {
container.insertBefore(child.cloneNode(true), null);
}
});
return container;
}
function insertAllAfter(containerNode, nodeOrNodeArrayToInsert, insertAfterNode) {
var frag, len, i;
// poor man's node and array check, should be enough for this
if (typeof nodeOrNodeArrayToInsert.nodeType !== "undefined" && typeof nodeOrNodeArrayToInsert.length === "undefined") {
throw new Error("Expected a single node or a node array");
}
if (typeof nodeOrNodeArrayToInsert.nodeType !== "undefined") {
ko.virtualElements.insertAfter(containerNode, nodeOrNodeArrayToInsert, insertAfterNode);
return;
}
if (nodeOrNodeArrayToInsert.length === 1) {
ko.virtualElements.insertAfter(containerNode, nodeOrNodeArrayToInsert[0], insertAfterNode);
return;
}
if (supportsDocumentFragment) {
frag = document.createDocumentFragment();
for (i = 0, len = nodeOrNodeArrayToInsert.length; i !== len; ++i) {
frag.appendChild(nodeOrNodeArrayToInsert[i]);
}
ko.virtualElements.insertAfter(containerNode, frag, insertAfterNode);
} else {
// Nodes are inserted in reverse order - pushed down immediately after
// the last node for the previous item or as the first node of element.
for (i = nodeOrNodeArrayToInsert.length - 1; i >= 0; --i) {
var child = nodeOrNodeArrayToInsert[i];
if (!child) {
return;
}
ko.virtualElements.insertAfter(containerNode, child, insertAfterNode);
}
}
}
// Mimic a KO change item 'add'
function valueToChangeAddItem(value, index) {
return {
status: 'added',
value: value,
index: index
};
}
function isAdditionAdjacentToLast(changeIndex, arrayChanges) {
return changeIndex > 0 &&
changeIndex < arrayChanges.length &&
arrayChanges[changeIndex].status === "added" &&
arrayChanges[changeIndex - 1].status === "added" &&
arrayChanges[changeIndex - 1].index === arrayChanges[changeIndex].index - 1;
}
function FastForEach(spec) {
this.element = spec.element;
this.container = isVirtualNode(this.element) ?
this.element.parentNode : this.element;
this.$context = spec.$context;
this.data = spec.data;
this.as = spec.as;
this.noContext = spec.noContext;
this.templateNode = makeTemplateNode(
spec.name ? document.getElementById(spec.name).cloneNode(true) : spec.element
);
this.afterQueueFlush = spec.afterQueueFlush;
this.beforeQueueFlush = spec.beforeQueueFlush;
this.changeQueue = [];
this.lastNodesList = [];
this.indexesToDelete = [];
this.rendering_queued = false;
// Remove existing content.
ko.virtualElements.emptyNode(this.element);
// Prime content
var primeData = ko.unwrap(this.data);
if (primeData.map) {
this.onArrayChange(primeData.map(valueToChangeAddItem));
}
// Watch for changes
if (ko.isObservable(this.data)) {
if (!this.data.indexOf) {
// Make sure the observable is trackable.
this.data = this.data.extend({trackArrayChanges: true});
}
this.changeSubs = this.data.subscribe(this.onArrayChange, this, 'arrayChange');
}
}
FastForEach.animateFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame || window.msRequestAnimationFrame ||
function(cb) { return window.setTimeout(cb, 1000 / 60); };
FastForEach.prototype.dispose = function () {
if (this.changeSubs) {
this.changeSubs.dispose();
}
};
// If the array changes we register the change.
FastForEach.prototype.onArrayChange = function (changeSet) {
var self = this;
var changeMap = {
added: [],
deleted: []
};
for (var i = 0, len = changeSet.length; i < len; i++) {
// the change is appended to a last change info object when both are 'added' and have indexes next to each other
// here I presume that ko is sending changes in monotonic order (in index variable) which happens to be true, tested with push and splice with multiple pushed values
if (isAdditionAdjacentToLast(i, changeSet)) {
var batchValues = changeMap.added[changeMap.added.length - 1].values;
if (!batchValues) {
// transform the last addition into a batch addition object
var lastAddition = changeMap.added.pop();
var batchAddition = {
isBatch: true,
status: 'added',
index: lastAddition.index,
values: [lastAddition.value]
};
batchValues = batchAddition.values;
changeMap.added.push(batchAddition);
}
batchValues.push(changeSet[i].value);
} else {
changeMap[changeSet[i].status].push(changeSet[i]);
}
}
if (changeMap.deleted.length > 0) {
this.changeQueue.push.apply(this.changeQueue, changeMap.deleted);
this.changeQueue.push({status: 'clearDeletedIndexes'});
}
this.changeQueue.push.apply(this.changeQueue, changeMap.added);
// Once a change is registered, the ticking count-down starts for the processQueue.
if (this.changeQueue.length > 0 && !this.rendering_queued) {
this.rendering_queued = true;
FastForEach.animateFrame.call(window, function () { self.processQueue(); });
}
};
// Reflect all the changes in the queue in the DOM, then wipe the queue.
FastForEach.prototype.processQueue = function () {
var self = this;
// Callback so folks can do things before the queue flush.
if (typeof this.beforeQueueFlush === 'function') {
this.beforeQueueFlush(this.changeQueue);
}
ko.utils.arrayForEach(this.changeQueue, function (changeItem) {
// console.log(self.data(), "CI", JSON.stringify(changeItem, null, 2), JSON.stringify($(self.element).text()))
self[changeItem.status](changeItem);
// console.log(" ==> ", JSON.stringify($(self.element).text()))
});
this.rendering_queued = false;
// Callback so folks can do things.
if (typeof this.afterQueueFlush === 'function') {
this.afterQueueFlush(this.changeQueue);
}
this.changeQueue = [];
};
// Process a changeItem with {status: 'added', ...}
FastForEach.prototype.added = function (changeItem) {
var index = changeItem.index;
var valuesToAdd = changeItem.isBatch ? changeItem.values : [changeItem.value];
var referenceElement = this.lastNodesList[index - 1] || null;
// gather all childnodes for a possible batch insertion
var allChildNodes = [];
for (var i = 0, len = valuesToAdd.length; i < len; ++i) {
var templateClone = this.templateNode.cloneNode(true);
var childContext;
if (this.noContext) {
childContext = this.$context.extend({
'$item': valuesToAdd[i]
});
} else {
childContext = this.$context.createChildContext(valuesToAdd[i], this.as || null);
}
// apply bindings first, and then process child nodes, because bindings can add childnodes
ko.applyBindingsToDescendants(childContext, templateClone);
var childNodes = ko.virtualElements.childNodes(templateClone);
// Note discussion at https://github.com/angular/angular.js/issues/7851
allChildNodes.push.apply(allChildNodes, Array.prototype.slice.call(childNodes));
this.lastNodesList.splice(index + i, 0, childNodes[childNodes.length - 1]);
}
insertAllAfter(this.element, allChildNodes, referenceElement);
};
// Process a changeItem with {status: 'deleted', ...}
FastForEach.prototype.deleted = function (changeItem) {
var index = changeItem.index;
var ptr = this.lastNodesList[index],
// We use this.element because that will be the last previous node
// for virtual element lists.
lastNode = this.lastNodesList[index - 1] || this.element;
do {
ptr = ptr.previousSibling;
ko.removeNode((ptr && ptr.nextSibling) || ko.virtualElements.firstChild(this.element));
} while (ptr && ptr !== lastNode);
// The "last node" in the DOM from which we begin our delets of the next adjacent node is
// now the sibling that preceded the first node of this item.
this.lastNodesList[index] = this.lastNodesList[index - 1];
this.indexesToDelete.push(index);
};
// We batch our deletion of item indexes in our parallel array.
// See brianmhunt/knockout-fast-foreach#6/#8
FastForEach.prototype.clearDeletedIndexes = function () {
// We iterate in reverse on the presumption (following the unit tests) that KO's diff engine
// processes diffs (esp. deletes) monotonically ascending i.e. from index 0 -> N.
for (var i = this.indexesToDelete.length - 1; i >= 0; --i) {
this.lastNodesList.splice(this.indexesToDelete[i], 1);
}
this.indexesToDelete = [];
};
ko.bindingHandlers.fastForEach = {
// Valid valueAccessors:
// []
// ko.observable([])
// ko.observableArray([])
// ko.computed
// {data: array, name: string, as: string}
init: function init(element, valueAccessor, bindings, vm, context) {
var value = valueAccessor(),
ffe;
if (isPlainObject(value)) {
value.element = value.element || element;
value.$context = context;
ffe = new FastForEach(value);
} else {
ffe = new FastForEach({
element: element,
data: ko.unwrap(context.$rawData) === value ? context.$rawData : value,
$context: context
});
}
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
ffe.dispose();
});
return {controlsDescendantBindings: true};
},
// Export for testing, debugging, and overloading.
FastForEach: FastForEach
};
ko.virtualElements.allowedBindings.fastForEach = true;
}));
+216
View File
@@ -0,0 +1,216 @@
// REPEAT binding for Knockout http://knockoutjs.com/
// (c) Michael Best
// License: MIT (http://www.opensource.org/licenses/mit-license.php)
// Version 2.1.0
(function(factory) {
if (typeof define === 'function' && define.amd) {
// [1] AMD anonymous module
define(['knockout'], factory);
} else if (typeof exports === 'object') {
// [2] commonJS
factory(require('knockout'));
} else {
// [3] No module loader (plain <script> tag) - put directly in global namespace
factory(window.ko);
}
})(function(ko) {
if (!ko.virtualElements)
throw Error('Repeat requires at least Knockout 2.1');
var ko_bindingFlags = ko.bindingFlags || {};
var ko_unwrap = ko.utils.unwrapObservable;
var koProtoName = '__ko_proto__';
if (ko.version >= "3.0.0") {
// In Knockout 3.0.0, use the node preprocessor to replace a node with a repeat binding with a virtual element
var provider = ko.bindingProvider.instance, previousPreprocessFn = provider.preprocessNode;
provider.preprocessNode = function(node) {
var newNodes, nodeBinding;
if (!previousPreprocessFn || !(newNodes = previousPreprocessFn.call(this, node))) {
if (node.nodeType === 1 && (nodeBinding = node.getAttribute('data-bind'))) {
if (/^\s*repeat\s*:/.test(nodeBinding)) {
var leadingComment = node.ownerDocument.createComment('ko ' + nodeBinding),
trailingComment = node.ownerDocument.createComment('/ko');
node.parentNode.insertBefore(leadingComment, node);
node.parentNode.insertBefore(trailingComment, node.nextSibling);
node.removeAttribute('data-bind');
newNodes = [leadingComment, node, trailingComment];
}
}
}
return newNodes;
};
}
ko.virtualElements.allowedBindings.repeat = true;
ko.bindingHandlers.repeat = {
flags: ko_bindingFlags.contentBind | ko_bindingFlags.canUseVirtual,
init: function(element, valueAccessor, allBindingsAccessor, xxx, bindingContext) {
// Read and set fixed options--these options cannot be changed
var repeatParam = ko_unwrap(valueAccessor());
if (repeatParam && typeof repeatParam == 'object' && !('length' in repeatParam)) {
var repeatIndex = repeatParam.index,
repeatData = repeatParam.item,
repeatStep = repeatParam.step,
repeatReversed = repeatParam.reverse,
repeatBind = repeatParam.bind,
repeatInit = repeatParam.init,
repeatUpdate = repeatParam.update;
}
// Set default values for options that need it
repeatIndex = repeatIndex || '$index';
repeatData = repeatData || ko.bindingHandlers.repeat.itemName || '$item';
repeatStep = repeatStep || 1;
repeatReversed = repeatReversed || false;
var parent = element.parentNode, placeholder;
if (element.nodeType == 8) { // virtual element
// Extract the "children" and find the single element node
var childNodes = ko.utils.arrayFilter(ko.virtualElements.childNodes(element), function(node) { return node.nodeType == 1;});
if (childNodes.length !== 1) {
throw Error("Repeat binding requires a single element to repeat");
}
ko.virtualElements.emptyNode(element);
// The placeholder is the closing comment normally, or the opening comment if reversed
placeholder = repeatReversed ? element : element.nextSibling;
// The element to repeat is the contained element
element = childNodes[0];
} else { // regular element
// First clean the element node and remove node's binding
var origBindString = element.getAttribute('data-bind');
ko.cleanNode(element);
element.removeAttribute('data-bind');
// Original element is no longer needed: delete it and create a placeholder comment
placeholder = element.ownerDocument.createComment('ko_repeatplaceholder ' + origBindString);
parent.replaceChild(placeholder, element);
}
// extract and remove a data-repeat-bind attribute, if present
if (!repeatBind) {
repeatBind = element.getAttribute('data-repeat-bind');
if (repeatBind) {
element.removeAttribute('data-repeat-bind');
}
}
// Make a copy of the element node to be copied for each repetition
var cleanNode = element.cloneNode(true);
if (typeof repeatBind == "string") {
cleanNode.setAttribute('data-bind', repeatBind);
repeatBind = null;
}
// Set up persistent data
var lastRepeatCount = 0,
notificationObservable = ko.observable(),
repeatArray, arrayObservable;
if (repeatInit) {
repeatInit(parent);
}
var subscribable = ko.computed(function() {
function makeArrayItemAccessor(index) {
var f = function(newValue) {
var item = repeatArray[index];
// Reading the value of the item
if (!arguments.length) {
notificationObservable(); // for dependency tracking
return ko_unwrap(item);
}
// Writing a value to the item
if (ko.isObservable(item)) {
item(newValue);
} else if (arrayObservable && arrayObservable.splice) {
arrayObservable.splice(index, 1, newValue);
} else {
repeatArray[index] = newValue;
}
return this;
};
// Pretend that our accessor function is an observable
f[koProtoName] = ko.observable;
return f;
}
function makeBinding(item, index, context) {
return repeatArray
? function() { return repeatBind.call(bindingContext.$data, item, index, context); }
: function() { return repeatBind.call(bindingContext.$data, index, context); }
}
// Read and set up variable options--these options can change and will update the binding
var paramObservable = valueAccessor(), repeatParam = ko_unwrap(paramObservable), repeatCount = 0;
if (repeatParam && typeof repeatParam == 'object') {
if ('length' in repeatParam) {
repeatArray = repeatParam;
repeatCount = repeatArray.length;
} else {
if ('foreach' in repeatParam) {
repeatArray = ko_unwrap(paramObservable = repeatParam.foreach);
if (repeatArray && typeof repeatArray == 'object' && 'length' in repeatArray) {
repeatCount = repeatArray.length || 0;
} else {
repeatCount = repeatArray || 0;
repeatArray = null;
}
}
// If a count value is provided (>0), always output that number of items
if ('count' in repeatParam)
repeatCount = ko_unwrap(repeatParam.count) || repeatCount;
// If a limit is provided, don't output more than the limit
if ('limit' in repeatParam)
repeatCount = Math.min(repeatCount, ko_unwrap(repeatParam.limit)) || repeatCount;
}
arrayObservable = repeatArray && ko.isObservable(paramObservable) ? paramObservable : null;
} else {
repeatCount = repeatParam || 0;
}
// Remove nodes from end if array is shorter
for (; lastRepeatCount > repeatCount; lastRepeatCount-=repeatStep) {
ko.removeNode(repeatReversed ? placeholder.nextSibling : placeholder.previousSibling);
}
// Notify existing nodes of change
notificationObservable.notifySubscribers();
// Add nodes to end if array is longer (also initially populates nodes)
for (; lastRepeatCount < repeatCount; lastRepeatCount+=repeatStep) {
// Clone node and add to document
var newNode = cleanNode.cloneNode(true);
parent.insertBefore(newNode, repeatReversed ? placeholder.nextSibling : placeholder);
newNode.setAttribute('data-repeat-index', lastRepeatCount);
// Apply bindings to inserted node
if (repeatArray && repeatData == '$data') {
var newContext = bindingContext.createChildContext(makeArrayItemAccessor(lastRepeatCount));
} else {
var newContext = bindingContext.extend();
if (repeatArray)
newContext[repeatData] = makeArrayItemAccessor(lastRepeatCount);
}
newContext[repeatIndex] = lastRepeatCount;
if (repeatBind) {
var result = ko.applyBindingsToNode(newNode, makeBinding(newContext[repeatData], lastRepeatCount, newContext), newContext, true),
shouldBindDescendants = result && result.shouldBindDescendants;
}
if (!repeatBind || (result && shouldBindDescendants !== false)) {
ko.applyBindings(newContext, newNode);
}
}
if (repeatUpdate) {
repeatUpdate(parent);
}
}, null, {disposeWhenNodeIsRemoved: placeholder});
return { controlsDescendantBindings: true, subscribable: subscribable };
}
};
});
File diff suppressed because it is too large Load Diff