Jeeves Barton
Jeeves Barton

Reputation: 3

Updating a knockout observable

Im having some trouble updating a knockout observable value. I need to pass the value from linkClick into showMenu.

When I manually update showMenu like this showMenu("Value"), the Value will get passed to the view fine. It needs to be a dynamic value however. This is essentially my code as it stands.

//View
<a data-bind="click: linkClick" data-sec="Value">Click Me</a>

<!-- ko if: showMenu() === 'Value' -->
    <ul class="Menu">
        <li>Link 1</li>
        <li>Link 2</li>
    </ul>
<!-- /ko -->

define(
  [''],
  function () {
    var _this = this;
    return {

        showMenu: ko.observable(""),
        linkClick: function(data, event) {

            var element = event.target,                    
                Menu = $(element).attr('data-sec');

            var myMenu = this.showMenu();
            this.showMenu(Menu);

        }
    }
});

Ive also tried using _this in the global scope instead of this however this produces a _this.showMenu() is not a function error. Please help.

PS. I have to write everything inside that first function definition.

Upvotes: 0

Views: 42

Answers (1)

Ja9ad335h
Ja9ad335h

Reputation: 5075

use data (which is your viewmodel) instead of this

function vm() {
  return {
    showMenu: ko.observable(""),
    linkClick: function(data, event) {
      var element = event.target,
        Menu = $(element).attr('data-sec');

      // use data instead of this
      data.showMenu(Menu);
    }
  }
}

ko.applyBindings(vm());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<a data-bind="click: linkClick" data-sec="Value">Click Me</a> 
<!-- ko if: showMenu() === 'Value' -->
<ul class="Menu">
  <li>Link 1</li>
  <li>Link 2</li>
</ul>
<!-- /ko -->

Upvotes: 2

Related Questions