Created
September 17, 2012 14:26
-
-
Save raiden-dev/3737661 to your computer and use it in GitHub Desktop.
KnockoutJS Custom Binding: pointer
This file contains 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
/** | |
* 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