knockout.jsutility-method

How to create a utility method in knockout JS?


<input type="text" id="txtFirstname" data-bind="value:firstName,valueUpdate:'afterkeydown'" />
<i data-bind="css:RequiredStyle(firstName)"></i>
  var ViewModel = function () {
    var self = this;

    self.firstName = ko.observable("Hello World!");

    self.RequiredFieldStyle=function (controlValue) {
        alert('called');
        var hasValue = controlValue().length;
        if (hasValue > 0) {
            return "fa fa-check-circle";
        } else {
            return "fa fa-exclamation-circle";
        }
    };
};

How does one create the utility method for the RequiredFieldStyle function in knockout.js?


Solution

  • If you need this to be reusable you could use a custom binding

    In your case something like this could work

    ko.bindingHandlers.checkIcon = {
                init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                    $(element).removeClass('fa-check-circle fa-exclamation-circle');
                    var v = ko.utils.unwrapObservable(valueAccessor());
                    $(element).addClass(v.length ? 'fa-check-circle' : 'fa-exclamation-circle');
                },
                update: function(element, valueAccessor, allBindings, context, bindingContext) {
                    $(element).removeClass('fa-check-circle fa-exclamation-circle');
                    var v = ko.utils.unwrapObservable(valueAccessor());
                    $(element).addClass(v.length ? 'fa-check-circle' : 'fa-exclamation-circle');
                }
            }
            
     var vm = {
       firstName:ko.observable('')
     }
     
     ko.applyBindings(vm);
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.css" rel="stylesheet"/>
    <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>
    
    <input type="text" data-bind="textInput:firstName"/>
    
    <span class="fa" data-bind="checkIcon:firstName"></span>