JSFiddle - React, Tailwind, and code Playground
by greenlaw110
HTML
<script src="https://github.com/downloads/SteveSanderson/knockout/jquery.tmpl.js"></script>
<script src="https://github.com/downloads/SteveSanderson/knockout/knockout-1.1.2.js"></script>
<div id="testTemplate">
Here is the output:
<div data-bind='template: {name: "itemTemplate1", data: myModel.items}'></div>
<div data-bind='template: {name: "itemTemplate2", foreach: myModel.items}'></div>
</div>
<script type="text/html" id="itemTemplate1">
{{each $data}}
<div id="item-$index" data-bind="myCustomBinder:$data,currentItem:$index">${name}</div>
{{/each}}
</script>
<script type="text/html" id="itemTemplate2">
<div data-bind="myCustomBinder2:$data">${name}</div>
</script>
JavaScript
var myModel = {
items: ko.observableArray([])
};
myModel.items().push({
name: 'pete',
age: 23
});
myModel.items().push({
name: 'daniel',
age: 26
});
ko.bindingHandlers.myCustomBinder = {
init: function(element, valueAccessor, allBindingsAccessor) {
// First get the latest data that we're bound to
var value = valueAccessor(),
allBindings = allBindingsAccessor();
// Next, whether or not the supplied model property is observable, get its current value
var valueUnwrapped = ko.utils.unwrapObservable(value);
var index = allBindings.currentItem;
// Do something on custom binder
alert(valueUnwrapped[index].name);
}
};
ko.bindingHandlers.myCustomBinder2 = {
init: function(element, valueAccessor, allBindingsAccessor) {
// First get the latest data that we're bound to
var value = valueAccessor(),
allBindings = allBindingsAccessor();
// Next, whether or not the supplied model property is observable, get its current value
var valueUnwrapped = ko.utils.unwrapObservable(value);
//var index = allBindings.currentItem;
// Do something on custom binder
alert(valueUnwrapped.name);
}
};
ko.applyBindings(myModel, $('div#testTemplate').get(0));