I have this function:
function make(place)
{
place.innerHTML = \"somthing\"
}
I used to do this with plain JavaScript and html:
A generic answer on how to handle click events with KnockoutJS...
Not a straight up answer to the question as asked, but probably an answer to the question most Googlers landing here have: use the click binding from KnockoutJS instead of onclick. Like this:
function Item(parent, txt) {
var self = this;
self.doStuff = function(data, event) {
console.log(data, event);
parent.log(parent.log() + "\n data = " + ko.toJSON(data));
};
self.doOtherStuff = function(customParam, data, event) {
console.log(data, event);
parent.log(parent.log() + "\n data = " + ko.toJSON(data) + ", customParam = " + customParam);
};
self.txt = ko.observable(txt);
}
function RootVm(items) {
var self = this;
self.doParentStuff = function(data, event) {
console.log(data, event);
self.log(self.log() + "\n data = " + ko.toJSON(data));
};
self.items = ko.observableArray([
new Item(self, "John Doe"),
new Item(self, "Marcus Aurelius")
]);
self.log = ko.observable("Started logging...");
}
ko.applyBindings(new RootVm());
.parent { background: rgba(150, 150, 200, 0.5); padding: 2px; margin: 5px; }
button { margin: 2px 0; font-family: consolas; font-size: 11px; }
pre { background: #eee; border: 1px solid #ccc; padding: 5px; }
Click log:
**A note about the actual question...*
The actual question has one interesting bit:
// Uh oh! Modifying the DOM....
place.innerHTML = "somthing"
Don't do that! Don't modify the DOM like that when using an MVVM framework like KnockoutJS, especially not the piece of the DOM that is your own parent. If you would do this the button would disappear (if you replace your parent's innerHTML you yourself will be gone forever ever!).
Instead, modify the View Model in your handler instead, and have the View respond. For example:
function RootVm() {
var self = this;
self.buttonWasClickedOnce = ko.observable(false);
self.toggle = function(data, event) {
self.buttonWasClickedOnce(!self.buttonWasClickedOnce());
};
}
ko.applyBindings(new RootVm());
Can be made visible with toggle...