SORU
20 EYLÜL 2011, Salı


Her zaman benim viewmodel yapmak kullanarak Nakavt harita eklentisi fazla kullanmak mıyım?

Ben hala öğrenme, doğru kullanım ve Nakavt buldum kendimi hızla uzaklaşmak hiç yazma ko.observable zaman ayarı benim viewmodel ve yerine sadece tanımlayan bir nesne değişmez ve geçen içinden eşleme eklentisi olan bir şey gibi

var viewModel = ko.mapping.fromJS(data);

ya da en azından, viewModel üzerinde bir öznitelik içine benim tüm veri doldurma çizgisinde bir şey gibi

var viewModel = { 
    ... events etc ... , 
    "data": ko.mapping.fromJS(data)
}

Dürüst olmak gerekirse, ben bu işi yapıyordum başlıca nedeni ko.observable ko.observableArray sürekli yazmak zorunda kalmak etrafında almak için. Sadece eğer var x = ko.observable() özel beyanname birlikte bırakarak her olumsuzlukları eğer varsa, bu iyi bir yaklaşım olduğundan ve anlamaya çalışıyorum. Ayrıca, bu konuda söyleyebileceğim, harita Eklentisi için tasarlanmış olan herhangi bir ajax çağrısı vb, yanıt olarak yük üzerinde değil, yapıyorum.

Nakavt ile iş, hala observables el ilan musun, tek tek, ya da eşleme ile gittin.kullandığım yöntemi fromJS? Çok sık harita eklentisi bu gibi kullanarak belirli olumsuzlukları vardır?

Düzenleme:

Spesifik Bir Örnek

In this article Steve yaparak onun viewModel ayarlar

var initialData = [ { ... } , { ... } ]; // json from the serializer
var viewModel = {
    gifts : ko.observableArray(initialData)
};

Normalde, sadece bu durum için ko.mapping.fromJS de, özellikle dizi içindeki nesneleri observables dönüştü olduğundan emin olmak için de kullanmak istiyorum. Ne yaptığına bakarak, benim yaklaşımı overkill gibi görünüyor ve gereksiz yük bir bit ekler.

CEVAP
11 NİSAN 2012, ÇARŞAMBA


Biraz daha Nakavt kullandıktan sonra, harita eklentisi eşleme süreci üzerinde çok daha ince taneli kontrolü verecek bazı ek seçenekler olduğunu fark ettim.

Özellikleri oluşturulan cinsi ve miktarını kontrol eder

Bunu yapmak için birkaç yolu vardır, ve bazı geçerim, ama sonuçta her şeyi gözlemlenebilir değil çünkü harita eklentisi hafif bir sonuca ulaştım.

Temelde, normal bir özellik olarak değişeceğini sanmıyorum o her şeyi bırakın ve sadece gözlemlemek istediğiniz belirli öğeleri dışarı observables olun.

mapping belirli özelliklerini atlar

Harita eklentisi özellikleri tamamen ignore include gibi şeyler belirterek sonuçta atlamak yapabilirsiniz. Bunların her ikisi de aynı şey, ters sadece başarmak.

Not: Örnekler knockout.js mapping plugin documentation yorum benim tarafımdan eklendi

Eşleme Eklentisi Bağımsız Değişken: include

Aşağıdaki parçacıktüm özelliklerini atlarkaynak nesneden o include argüman üzerinden geçti.

// specify the specific properties to include as observables in the end result 
var mapping = {
    // only include these two properties
    'include': ["propertyToInclude", "alsoIncludeThis"]
}

// viewModel will now only contain the two properties listed above, 
//    and they will be observable
var viewModel = ko.mapping.fromJS(data, mapping);

Eşleme Eklentisi Bağımsız Değişken: ignore

Eğer isterseniz sadecebazı özelliklerini atlarkaynak nesne, aşağıda gösterildiği gibi ignore argüman kullanın. Kaynağı tüm özellikleri observables belirtilen özellikler dışında bir nesne yapar.

// specify the specific properties to omit from the result, 
//    all others will be made observable
var mapping = {
    // only ignore these two properties
    'ignore': ["propertyToIgnore", "alsoIgnoreThis"]
}

// viewModel will now omit the two properties listed above, 
//    everything else will be included and they will be an observable
var viewModel = ko.mapping.fromJS(data, mapping);

Özellikleri ne kontrolü ya da gözlemlenebilir

Ama gözlemlenebilir yapılması gereken düşünmüyorsun özellikleri (sebebi ne olursa olsun) eklemek istiyorsanız, harita eklentisi yardımcı olabilecek bir şey vardır.

Eşleme Eklentisi Bağımsız Değişken: copy

Eğer eşleme eklenti sadece düz özellikleri kopyalayın ve onları gözlemlenebilir yapmak istiyorsanız, aşağıda gösterildiği gibi bu değişkeni kullanın.

// tell the mapping plugin to handle all other properties normally, 
//    but to simply copy this property instead of making it observable
var mapping = {
    'copy': ["propertyToCopy"]
}
var viewModel = ko.mapping.fromJS(data, mapping);

Eşleme işlemi üzerinde tam kontrol sahibi

Eğer eşleme sürecinde ortaya çıkan şey üzerinde 0 kontrol sahibi olmak istiyorsanızsizin nesneleri kilitler ve abonelikleri koymak için yeteneği dahil olmak üzeresonra kullanmak istediğiniz "" seçeneği oluşturun.

düz hesaplanan özellikleri ile sonuçlanır

Burada results bir özelliği olan bir nesne için bir ajax çağrısından bir harita verileri nerede olduğumu bir örnek. Gözlemlenebilir bir şey istemedim ve ben sadece diğer basit özellikleri nesne üzerinde yapılabilecek basit oluşturulan bir özellik istedim. Belki de en çarpıcı örnek, ama değil işlevselliği gösterir.

var searchMappingConfig = {
    // specific configuration for mapping the results property
    "results": {
                    // specific function to use to create the items in the results array
        "create": function (options) {
            // return a new function so we can have the proper scope/value for "this", below
            return new function () {

                // instead of mapping like we normally would: ko.mapping.fromJS(options.data, {}, this);
                // map via extend, this will just copy the properties from the returned json element to "this"
                // we'll do this for a more light weight vm since every last property will just be a plain old property instead of observable
                $.extend(this, options.data);

                // all this to add a vehicle title to each item
                this.vehicleTitle = this.Year   "<br />"   this.Make   " "   this.Model;
                }, this);
            };
        }
    }
}

Abonelikleri ve kapatma, ve, aman inceliyorum

Başka bir durum varsa, sonuç olarak kilitler ve abonelikleri istiyorsanız. Bu örnek, bütünüyle dahil olması için çok uzun ama bir araç/model hiyerarşi olun. Verilen bir (üst) model BM-etkinleştirildi BM etkin olmak için tüm modeller (çocuk) istedim ve bu aboneliği bitirmek istedim.

// here we are specifying the way that items in the make array are created, 
//    since makes has a child array (Models), we will specify the way that 
//    items are created for that as well
var makesModelsMappingConfig = {
   // function that has the configuration for creating makes
   "create": function (options) {
      // return a new function so we can have the proper 
      //    scope/value for "this", below
      return new function () {

         // Note: we have a parent / child relationship here, makes have models. In the 
         //    UI we are selecting makes and then using that to allow the user to select 
         //    models. Because of this, there is going to be some special logic in here 
         //    so that all the child models under a given make, will automatically 
         //    unselect if the user unselects the parent make.

         // make the selected property a private variable so it can be closure'd over
         var makeIsSelected = ko.protectedComputed(false);

         // expose our property so we can bind in the UI
         this.isSelected = makeIsSelected;

         // ... misc other properties and events ...

         // now that we've described/configured how to create the makes, 
         //    describe/configure how to create the models under the makes
         ko.mapping.fromJS(options.data, {
            // specific configuration for the "Models" property                  
            "Models": {
               // function that has the configuration for creating items 
               //    under the Models property
               "create": function (model) {

                  // we'll create the isSelected as a local variable so 
                  //    that we can flip it in the subscription below, 
                  //    otherwise we wouldnt have access to flip it
                  var isSelected = ko.protectedComputed(false);

                  // subscribe to the parents "IsSelected" property so 
                  //    the models can select/unselect themselves
                  parentIsSelected.current.subscribe(function (value) {
                     // set the protected computed to the same 
                     //    value as its parent, note that this 
                     //    is just protected, not the actual value
                     isSelected(value);
                  });


                  // this object literal is what makes up each item 
                  //    in the Models observable array 
                  return {
                     // here we're returning our local variable so 
                     //    we can easily modify it in our subscription
                     "isSelected": isSelected,

                     // ... misc properties to expose 
                     //     under the item in the Model array ...

                  };
               }
            }
         }, this);
      };
   }
};

Sonuçta, ne buldum nadiren eklentisi geçersin bir nesne 0 ihtiyaç vardır ve nadiren 0 gözlemlenebilir olması gerekir. Eşleme ile yapılandırma seçenekleri kazmak ve karmaşık ve basit nesneleri her türlü oluşturun. Bu fikir sadece ihtiyacınız olan her şey, hiçbir şey daha fazla veya daha az almak için.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • eHow

    eHow

    27 NİSAN 2006
  • jesiel santos

    jesiel santo

    15 Ocak 2009
  • MuscleProdigyTV

    MuscleProdig

    8 Ocak 2011