Reputation: 2135
My presumption is that the KnockOutJs "visible" binding is two-way, so if I hide an dom element bound to a viewmodel property, a subscription to the observable would update. My sample in JsBin http://jsfiddle.net/zb6E9/20/ shows that if the observable is changed the subscription fires but if the dom element changes, the subscription does not fire.
I must be missing something, but what to do to make the jQuery button fire the subscription?
Html:
<input id="firstNameInput" data-bind="value: firstName, visible: isVisible" value="First" /><br />
<input data-bind="value: lastName" value="Last" /><br />
The name is <span data-bind="text: fullName"></span><br />
<input type="button" data-bind="click: changeVisibility" value="Change Visibility using KnockOut" /><br />
<input type="button" onclick="changeVisibilityJQuery()" value="Change Visibility Using jQuery" />
Javascript:
function changeVisibilityJQuery()
{
if($('#firstNameInput').is(':visible')){
$('#firstNameInput').hide();
} else {
$('#firstNameInput').show();
}
}
function AppViewModel() {
var self = this;
self.firstName = ko.observable('First');
self.lastName = ko.observable('Last');
self.isVisible = ko.observable(true);
self.changeVisibility = function(){
var v = self.isVisible() || false;
self.isVisible(!v);
};
self.isVisible.subscribe(function(bool) {
if (bool) {
// DO SOMETHING SUCH AS
self.firstName(self.firstName() + " " + bool);
}
});
self.fullName = ko.computed(function() {
return self.firstName() + " " + self.lastName();
});
}
ko.applyBindings(new AppViewModel());
Upvotes: 0
Views: 1036
Reputation: 15003
Since, as Michael Best has pointed out, there's no way for Knockout to detect an arbitrary visible change caused by outside code, the key is to make any code that has to change visibility do it by setting an observable
used in a visible
binding (so Knockout knows what's going on) rather than by manipulating the DOM directly. It's almost always best to let Knockout do all the DOM manipulation, either natively or through custom bindings. One of the most important points of MV* is that you have a single authority for updating views rather than a free-for-all.
Upvotes: 1