czwartek, 24 maja 2012

Knockout - odc. 4

W odcinku nr.4 dla Knockout trochę uzupełnień do zagadnień poruszanych w odc. 1.

Inna postać view modelu

var viewmodel = function() {

this.id = ko.observable(data.Id);

this.name = ko.observable(data.name);

this.formatCurrency = function(value) {

          return “$”  + value().toFixed(2);

};

};

ko.applyBindings(new viewmodel());

<span data-bind=”text: formatCurrency(price)”></span>

http://jsFiddle.net

Wsparcie w Visual Studio

  • Intellisense
  • Nuget
  • Web Essentials
  • Web Standards Update
  • WoVS Default Browser Switcher
  • JSLint
  • CSSCop
  • Resharper 6

Data binding - uzupełnienia

var product = {   //binding bez aktualizacji

id:  15900,

name: “Robaki”,

price: 46.99

};

ko.applyBindings(product);

ko.observable() - binding dwukierunkowy

Computed  // wartości wyliczane, zamiast starszych dependentObservable

vm = {

id:  ko.observable(1),

price:  ko.observable(46.99),

quntity: ko.observable(2000)

};

vm.extendedPrice = ko.computed( function () {

return this.product() ?

this.price()  * parseInt(“0” + this.quantity(), 10)  :  0;

}, vm);

Computed converter 

vm.extendedPrice = ko.computed({

read: function() {

},

write: function(value) {     

},

owner:  vm

});

ObservableArray

var Product = function() {

this.id = ko.observable();

this.price = ko.observable();

this.photo = ko.observable();

};

var vm = {

products:  ko.observableArray([]),

load:  function() {

       $.each(sampleData.data.Products, function(i, p) {

                     vm.products.push( new Product()

                       .id(p.Id)

                       .price(p.Price)

                       .photo(p.Photo)

                );

       });

}

};

<span data-bind=”text:  products().length”></span>

vm.sortProducts = function() {

      vm.products.sort(

              function(left, right) {

                      return left.name().toLowerCase() == right.name().toLowerCase()

                      ?  0 :  (left.name().toLowerCase()  < right.name().toLowerCase() ? -1 : 1)

              }

      );

};

data-bind=”enable:  itemToAdd().length > 0”

Subskrybowanie się na zmiany

var sub = vm.selectedItem.subscribe(function() {

}, vm);

sub.dispose();  //koniec subskrypcji

Brak komentarzy: