Reputation: 220
I have a div that would need to pop-up when an outside button is pressed.
Display is a computed observable in the script updated when a subscriber function updates and observable.
self.Screen5Visible = ko.observable(false);
self.Display = ko.computed(function () {
if (self.Screen5Visible() == false) {
alert("here1");
return 'none';
} else {
alert("here2");
return 'block';
}
});
Screen5shouter.subscribe(function (newValue) {
alert("subscriber" + newValue);
self.Screen5Visible(newValue);
}, self, "change");
self.Hide = function() {
self.Screen5Visible(false);
};
The Screen5shouter successfully gets true when called from outside viewmodel. I get to "here2" and supposedly return 'block' with computable. However the binding does not seem to work like this.
Regular javascript would work with getElementId. Also the hide function, which is data-bound on an image in div successfully updates the Display() binding, the div does recieve a 'none' value.
Thank you for help.
Upvotes: 0
Views: 173
Reputation: 7941
I think your problem is with the display: Display()
and more specifically the Display()
. Knockout is evaluating the function on render and then it is done with it. It is no longer an observable from that point onward. I believe that it needs to be display: Display
for knockout to subscribe to the Display property to have the effect that you are looking for.
From
<div id="Screen5" class="grid-item modalBox" data-bind="style: { display: Display() }"></div>
To
<div id="Screen5" class="grid-item modalBox" data-bind="style: { display: Display}"></div>
Upvotes: 1
Reputation: 346
So I got a working example for you using the visible binding. Hopefully this will help you achieve what you initially intended.
function Screen5 () {
this.Screen5Visible = ko.observable(false);
var self = this
this.show = function () {
self.Screen5Visible(true)
}
this.hide = function() {
self.Screen5Visible(false);
}
}
ko.applyBindings(Screen5)
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div id="Screen5" class="grid-item modalBox" data-bind="visible: Screen5Visible">
screen 5
</div>
<div id="Screen6" class="grid-item modalBox">
screen 6
</div>
<button data-bind="click: show">
Show Screen 5
</button>
<button data-bind="click: hide">
Hide Screen 5
</button>
Upvotes: 1