Last active
January 1, 2016 11:59
-
-
Save mbest/8141724 to your computer and use it in GitHub Desktop.
Tags each binding and records which ones are actually used. Later, you can log which ones haven't been used using `ko.outputUnusedBindings` (this also clears the log).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Output Unused Bindings for Knockout 3+ | |
(c) Michael Best | |
License: MIT (http://www.opensource.org/licenses/mit-license.php) | |
*/ | |
(function (ko) { | |
var originalGetBindingAccessors = ko.bindingProvider.instance.getBindingAccessors; | |
if (!originalGetBindingAccessors) { | |
throw Error('getBindingAccessors not found'); | |
} | |
function getNodeText(node) { | |
if (node.childNodes.length > 0) { | |
node = node.cloneNode(false); | |
} | |
return (node.outerHTML || new XMLSerializer().serializeToString(node)); | |
} | |
var allBindings = []; | |
function recordBinding(nodeText, binding, accessor) { | |
var record = { | |
used: false, | |
info: binding + ': ' + accessor + '; node: ' + nodeText | |
}; | |
allBindings.push(record); | |
return record; | |
} | |
function markUsed(record) { | |
record.used = true; | |
} | |
function outputUnusedBindings() { | |
var unused = ko.utils.arrayFilter(allBindings, function(record) { | |
return !record.used; | |
}); | |
if (unused.length) { | |
console.warn('' + unused.length + " unused bindings out of " + allBindings.length); | |
ko.utils.arrayForEach(unused, function(record) { | |
console.log(record.info); | |
}); | |
} else { | |
console.log("No unused bindings out of " + allBindings.length); | |
} | |
allBindings = []; | |
return unused; | |
} | |
ko.bindingProvider.instance.getBindingAccessors = function (node) { | |
var bindings = originalGetBindingAccessors.apply(this, arguments); | |
if (bindings) { | |
var nodeText = getNodeText(node); | |
ko.utils.objectForEach(bindings, function(binding, accessor) { | |
var record = recordBinding(nodeText, binding, accessor); | |
bindings[binding] = function () { | |
if (record) { | |
markUsed(record); | |
record = null; | |
} | |
return accessor(); | |
}; | |
}); | |
bindings._catchAllBindingsCall = function() { | |
console.warn('Deprecated use of allBindings as a function on node ' + nodeText); | |
} | |
} | |
return bindings; | |
}; | |
ko.outputUnusedBindings = outputUnusedBindings; | |
})(ko); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment