Search code examples
javascriptknockout.jsknockout-mapping-plugin

knockout simple binding issue


It could be one of the simplest forms of the knockout binding,

Couldn't find out what is the problem here :

Fiddle:

http://jsfiddle.net/qfntcfn8/

            <input data-bind="text:newGroupName" type="text" />
            <button class="btn" type=button data-bind="click: addGroup()">
                Add Group
            </button>

ViewModel :

    var vm = $(function() {
        function baseViewModel() {
            var self = this;
            self.newGroupName = ko.observable();
            self.addGroup = function () {
                console.log(ko.toJSON(self.newGroupName)); // Expected newGroupName entered data
            };
        }
        var viewModel = new baseViewModel();
        ko.mapping.fromJS(viewModel);
        ko.applyBindings(viewModel, document.getElementById("Box"));
    });

I expect to get newGroupName bound text as string after a click.


Solution

  • When binding input value, you need to use the value binding-handler:

    <input data-bind="value: newGroupName" type="text" />
    

    Also, since newGroupName is an observable function, you need to invoke it to get its value:

    console.log(self.newGroupName())