How to clear/remove observable bindings in Knockout.js?

后端 未结 9 1959
忘了有多久
忘了有多久 2020-11-29 16:40

I\'m building functionality onto a webpage which the user can perform multiple times. Through the user\'s action, an object/model is created and applied to HTML using ko.app

9条回答
  •  悲哀的现实
    2020-11-29 17:31

    You could try using the with binding that knockout offers: http://knockoutjs.com/documentation/with-binding.html The idea is to use apply bindings once, and whenever your data changes, just update your model.

    Lets say you have a top level view model storeViewModel, your cart represented by cartViewModel, and a list of items in that cart - say cartItemsViewModel.

    You would bind the top level model - the storeViewModel to the whole page. Then, you could separate the parts of your page that are responsible for cart or cart items.

    Lets assume that the cartItemsViewModel has the following structure:

    var actualCartItemsModel = { CartItems: [
      { ItemName: "FirstItem", Price: 12 }, 
      { ItemName: "SecondItem", Price: 10 }
    ] }
    

    The cartItemsViewModel can be empty at the beginning.

    The steps would look like this:

    1. Define bindings in html. Separate the cartItemsViewModel binding.

        
          
    2. The store model comes from your server (or is created in any other way).

      var storeViewModel = ko.mapping.fromJS(modelFromServer)

    3. Define empty models on your top level view model. Then a structure of that model can be updated with actual data.

        
          storeViewModel.cartItemsViewModel = ko.observable();
          storeViewModel.cartViewModel = ko.observable();
       
      
    4. Bind the top level view model.

      ko.applyBindings(storeViewModel);

    5. When the cartItemsViewModel object is available then assign it to the previously defined placeholder.

      storeViewModel.cartItemsViewModel(actualCartItemsModel);

    If you would like to clear the cart items: storeViewModel.cartItemsViewModel(null);

    Knockout will take care of html - i.e. it will appear when model is not empty and the contents of div (the one with the "with binding") will disappear.

提交回复
热议问题