Skip to content

Instantly share code, notes, and snippets.

@raiden-dev
Created September 17, 2012 14:26
Show Gist options
  • Save raiden-dev/3737661 to your computer and use it in GitHub Desktop.
Save raiden-dev/3737661 to your computer and use it in GitHub Desktop.
KnockoutJS Custom Binding: pointer
/**
* KO: Collects and cache pointers to elements.
* @param {string|object} Binding value.
* @config {string} The pointer's id.
* @config {object}
* {obArray} [ob=pointers]
* Observable Array to store cache.
* {string} [id] The pointer's id.
* @example
* // View
* <div data-bind="pointer: 'hello'"></div>
* <div data-bind="pointer: 'world'"></div>
* // ViewModel
* pointers.get('hello'); // returns first div element
*/
ko.bindingHandlers.pointer = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor();
var pointers = (typeof value === 'object')
? valueAccessor().ob
: viewModel.pointers || (function() {
viewModel.pointers = ko.observableArray();
return viewModel.pointers;
}());
var id = (typeof value === 'object') ? value.id : value;
if (!pointers.get) {
pointers.get = function(id, i) {
var i = i || 0;
return this()[i] && (this()[i].id == id && this()[i].el || this.get(id, i+1));
}
}
pointers.push({ id: id, el: element });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment