Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout click binding strange behavior

Trying to get basic Knockout click binding set up, as per the example below:

<button id="btn-a" class="btn" data-bind="css: {'btn-primary':mode() == 'manual'}, click: $root.mode('manual')">Manual</button>
<button id="btn-b"  class="btn" data-bind="css: {'btn-primary':mode() == 'automatic'}, click: $root.mode('automatic')">Automatic</button>

<label>MODE: </label><span data-bind="text:mode()"></span>  

<script>

$(function () {

    var TestModel = function() {        
        var self = this;
        this.mode = ko.observable('manual');
    };

    var testModel = new TestModel();
    window.testModel = testModel;
    ko.applyBindings(testModel);

});

Fiddle: http://jsfiddle.net/aq85wk65/

However, running into two issues:

  1. The binding causes the mode() value to start out as 'automatic', even though we explicitly initialize it to 'manual'.
  2. Whenever a button is clicked, the javascript console shows:

Uncaught TypeError: h.apply is not a function

like image 838
Yarin Avatar asked Apr 20 '15 19:04

Yarin


People also ask

What is binding in Knockout?

A binding context is an object that holds data that you can reference from your bindings. While applying bindings, Knockout automatically creates and manages a hierarchy of binding contexts. The root level of the hierarchy refers to the viewModel parameter you supplied to ko. applyBindings(viewModel) .

What is the function of Knockout?

A knockout, as related to genomics, refers to the use of genetic engineering to inactivate or remove one or more specific genes from an organism. Scientists create knockout organisms to study the impact of removing a gene from an organism, which often allows them to then learn something about that gene's function.

What is Knockout language?

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.


1 Answers

You need to wrap your click handlers in function:

http://jsfiddle.net/aq85wk65/1/

<button id="btn-a" class="btn" data-bind="css: {'btn-primary':mode() == 'manual'}, click: function(){$root.mode('manual')}">Manual</button>

see http://knockoutjs.com/documentation/click-binding.html

like image 191
dfperry Avatar answered Sep 30 '22 14:09

dfperry