knockout-repeat.js 9.83 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 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 };
    }
};
});