Tuhina Singh
Tuhina Singh

Reputation: 1007

Click binding is not working

I am creating this simple page with click binding on a button which doesn't seem to be working. Here is the code:

<!DOCTYPE html>
<html>    
  <head>
        <script type="text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script> 
  </head>

  <body>
    <div class="banner-bottom" width="100%" >   
    <div class="floatleft"><button  data-bind="click: $root.showActivity">click me </button></div>
    <div class="floatright">
        <div data-bind="if: showActivityMenu">here is a message!</div>      
        <div class="inner"> some values here</div>
    </div>
    <div style="clear:both;"></div>
</div>  
  </body>
<script>
function AAsearchViewModel() {
    var self = this;
    self.showActivityMenu =  ko.observable(true);
    self.showActivity = function () {
        self.showActivityMenu = ko.observable(false);
    };
}

ko.applyBindings(new AAsearchViewModel());

</script>
</html>

On the click binding, I have tried to both use and remove $root and $parent but that has no impact on output. Any clues what am doing wrong here?

Upvotes: 0

Views: 287

Answers (1)

dotnetom
dotnetom

Reputation: 24901

Observables are functions, so in your function showActivity instead of assigning a new value to observable showActivityMenu you need to call it as a function to assign a new value. Change this code:

self.showActivity = function () {
    self.showActivityMenu = ko.observable(false);
};

with this:

self.showActivity = function () {
    self.showActivityMenu(false);
};

You can read more about what observables are and how to use them in knockout documentation. Pay special attention to section Reading and writing observables

Upvotes: 2

Related Questions