Thursday, August 17, 2017

How to solve KnockOut JS observable object not update with Canada Post autocomplete

when i integrate the Canada Post Autocomplete with an KnockOut JS web application, it looks very smooth, all the street related fields had been populated on autocomplete selection.

however, the observable object that binding to the control did not update automatically.


From Canada Post web site, I found this sample code for my own customization on auto populate event

  1. <script type="text/javascript">
  2.  
  3. addressComplete.listen('load', function(control) {
  4. control.listen("populate", function (address) {
  5. document.getElementById("line1").value = address.Line1;
  6. });
  7. });
  8.  
  9. </script>

I try use this in my javascript, but it never work out. actually we only need to setup the controller listen event.

  var fields = [
             {
                 element: customerType + "street-address", field: "Line1"
             },
             {
                 element: "street-address2", field: "Line2", mode: pca.fieldMode.POPULATE
             },
             {
                 element: "city", field: "City", mode: pca.fieldMode.POPULATE
             },
             {
                 element: "province", field: "ProvinceCode", mode: pca.fieldMode.POPULATE
             },
             {
                 element: "postalCode", field: "PostalCode"
             },
             { element: "country", field: "CountryIso3", mode: pca.fieldMode.COUNTRY }
        ],

 options = {
               key: window.MyOwn.canadaPostKey
           },
          control = new pca.Address(fields, options);
        control.listen('populate', function (address) {
            customer.streetAddress(address.Line1);
            customer.city(address.City);
            customer.province(address.ProvinceCode);
            customer.postalCode(address.PostalCode);
            customer.country(address.CountryIso3);
        });






No comments:

Post a Comment