Just like you would explicitly set a value in code, you can set your observable values from the console like this:
viewModel.showDiv(true);
Pregunta
How can I trigger a data-bind property from browser tools? In the example below, how can I set showDiv to true or false from browser tools?
<div data-bind="visible:showDiv">Text</div>
Solución 2
Just like you would explicitly set a value in code, you can set your observable values from the console like this:
viewModel.showDiv(true);
Otros consejos
first, you don't trigger a data-bind, you can trigger an observable bound to a binding handler inside the data-bind,
where in your example, suppose that showDiv
is an observable, whenever you update that observable, it will trigger the update method of the visible
binding handler in your data-bind.
now as generic way not only limited to your case,
the simplest way is to make use of the $0
shortcut in developer tools ( Chrome & Firefox ) which will get you the last inspected DOM elements, along with either ko.dataFor
or ko.contextFor
methods, where they accept a DOM element as an argument.
whenever you want to see the underlying view model for any element you see on the page, and to update your view model's property ( in case they are observables ), do the following:
$0
variabl )now you can get the underlying view model behind that DOM element by using ko.dataFor( $0 )
ko.dataFor( $0 ).showDiv( true ); // your div is visible
ko.dataFor( $0 ).showDiv( false ); // not visible
in a more complex scenarios ( inside a foreach, or when having nested view models), you might want to use ko.contextFor( $0 )
Is there a real requirement to do this from browser tools? Can't you just create a button that calls a function in your view model to toggle it's value if it's for testing?
In your viewmodel (assuming you have an observable for showDiv
):
var self = this;
self.showDiv = ko.observable(true);
self.toggleDiv = function () {
self.showDiv(!self.showDiv());
}
Then:
<div data-bind="visible:showDiv">Text</div>
<input type="button" value="Toggle" data-bind="click: toggleDiv" />
Example in: JSFiddle
Otherwise I'd just create a breakpoint in the JS file and use the console to change it's value.