I am having trouble with my knockoutjs click binding, it seems to have stopped working and I am not sure why. The click binding is in a template as shown below.
The version I am using
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script>
My template
<ul id="runners" data-bind="template: {name:'runner-template', foreach:employees}"></ul>
<script type="text/html" id="runner-template">
<li class="runner" data-bind="click: runnerSelected.bind($data, Id(), Name())">
<span data-bind='text: Name'></span>
</li>
</script>
My javascript function exists outside of my view model
function runnerSelected(id, name) {
sponsoredRunner.id = id;
sponsoredRunner.name = name;
$("#sponsoredRunner").html(name);
console.log('~~ click on selected runner ['+JSON.stringify(sponsoredRunner)+']');
}
I load the view model from an asynchronous call
var temp = {};
temp.employees = [];
for(var i=0 ; i<result.employees.length ; i++) {
temp.employees.push(result.employees[i]);
}
var results = ko.mapping.fromJS(temp);
ko.cleanNode(document.getElementById('runners'));
ko.applyBindings(results, document.getElementById('runners'));
There is no output in the console to let me know where the problem is.
Any thoughts?
The problem was unrelated, I was hiding the ul elements using jquery.blur() on a setTimeout. The timeout was 100ms, turns out that was putting jquery and knockout in a race.
The code became cleaner during this process as well, so posting for completeness.
<ul id="runners" data-bind="template: {name:'runner-template', foreach:employees}"></ul>
<script type="text/html" id="runner-template">
<li class="runner" data-bind="click: $parent.runnerSelected">
<span data-bind='text: Name'></span>
</li>
</script>
And the javascript..
result.runnerSelected = function(data,event) {
$("#runners").hide();
sponsoredRunner.id = data.Id;
sponsoredRunner.name = data.Name;
$("#sponsoredRunner").html(sponsoredRunner.name);
}
ko.cleanNode(document.getElementById('runners'));
ko.applyBindings(result, document.getElementById('runners'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.