niedziela, 27 maja 2012

Knockout - odc. 8

Na obecny moment ten odcinek o Knockout będzie ostatnim, a w nim krótko nt. komunikacji ajax (wykorzystanie jQuery), change tracking oraz konwersji JSON na obiekty z observable i odwrotnie.

Ładowanie i zapisywanie danych

my.vm = function() {

products: ko.observableArray([]),

loadProductsCallback: function(json) {

          $.each(json, function(i, p) {

                          vm.products.push( new Product()

                                             .id(p.Id)

                                             .price(p.Price)

                                             .photo(p.Photo)

                                     );

            });

},

loadProducts = function() {

         my.productService.getProducts(my.vm.loadProductsCallback);

};

return {

       products: products,

       loadProducts: loadProducts,

       loadProductsCallback: loadProductsCallback

};

} ();

(function(my) {

“use strict”;

my.productService = {

         getProducts: function(callback) {

                 my.ajaxService.ajaxGetJson(“GetProducts”, null, callback);

         }

};

} (my));

(function(my) {

“use strict”;

var serviceBase = ‘/Product’,

       getSvcUrl =  function(method) {  return serviceBase +  method;  };             

my.ajaxService = (function() {

         var ajaxGetJson: function(method, jsonIn, callback) {

                 $.ajax({

                          url: getSvcUrl(method),

                          type: “GET”,

                          data: ko.toJSON(jsonIn),

                          dataType: “json”,

                          contentType:  “application/json”,

                          success:  function(json) {

                                   callback(json);

                          }

                 }

         });

};

return {

       ajaxGetJson: ajaxGetJson

};

}

Serwis produktów - kontroler ASP.NET MVC

Change tracking

pakiet Knockout.ChangeTracker

vm.tracker = new ChangeTracker(viewModel);

vm.tracker().somethingHasChanged();  //sprawdzenie

vm.tracker().markCurrentStateAsClean;

Mapping

Pakiet z konwersją JSON na obiekt z observables i odwrotnie

  • ko.mapping.fromJS(result)
  • ko.mapping.toJSON(model())

Brak komentarzy: