Skip to main content

knockoutjs custom bindings

Hi, i'm going to share the code sample for custom bindings in knockoutjs

I have an requirement to count and display to total employees. if have more then zero employee in employee-list, count and display.

In the 1st step, code sample for view model.

<script type="text/javascript">

// declare observable array
var totalEmployee = ko.observableArray([]);

try
{
    //get employee list form search employee method.
    var empList = searchEmployee();

    //push all items in totalEmployee array collection.
    if (empList !== undefined && empList.count > 0) {
        $.each(empList, function (i, v) {
            totalEmployee.push({ Id: v.empId, EmpName: v.empName });
        });
    };
}
catch (e) {
             //Toto: insert to logg, if any.
              console.log(e.stack);
}
finally { }


</script>

In the 2nd step, code sample for view.

<!-- ko if: totalEmployee -->
     Total Employee(<!--ko text: totalEmployee --><!--/ko-->
<!-- /ko -->

<!-- ko ifnot: totalEmployee -->
     Total Employee(0)
<!-- /ko -->