I have a checkbox bound to my KOJS model.
<input type="checkbox" data-bind="checked:settings.remember">
I’m trying to update the database when the user changes the value of the checkbox. However, the viewmodel is updated after these jQuery functions:
$("input[type='checkbox']").click(function(){ });
$("input[type='checkbox']").change(function(){ });
$("input[type='checkbox']").mouseup(function(){ });
To put it another way, when I peek into my viewModel inside of those functions, it will return the value of the checkbox’s value before the user had changed it. So if the checkbox was once true and now tells me false (and displays as false), the viewModel will still say true.
Is there some other jQuery function I could use that might occur after the binding occurs? Or can you think of any other clever way to call a function after my viewModel variable has changed? Note that my current viewModel declaration is:
var viewModel = {};
//...get some data from AJAX calls
ko.mapping.fromJSON(data, viewModel.'+file+');
where file is some dynamic value (I draw my viewModel from multiple databases)
I can solve the above problem with a hacky solution below (see my answer), but RP Niemeyer’s answer suggests there is a better way with manual subscriptions. So far I haven’t been able to figure out defining things within my viewModel along with using the mapping plugin.
Here’s my code so far, though, of course, it won’t work on the JSFiddle.
Generally, a good choice for this type of thing is to handle it in your view model itself. For example, you can use a manual subscription against
settings.remember(if it is an observable) and trigger your database call.The second argument to the
subscribecall determines the value ofthiswhen the function runs.If you are really forced to interact with your field changing outside of Knockout, then you would want to hook up a “change” handler, but not until after ko.applyBindings has been called. Then your change event handler will run after the change handler that Knockout has already added to the element. However, if your content is in a template and gets re-rendered, then your handler would be lost.
I would highly recommend using the manual subscription approach.