Change observable value on dropdown change Knockout Js

后端 未结 2 1351
清酒与你
清酒与你 2021-02-04 11:21

I have this dropdown which have options if vehicle is new or used.


                        
    
提交评论

  • 2021-02-04 11:42

    If you're using the ko mapping plugin you can intercept the creation of a new object and set up the subscription there. If you have a whole list of items and you want to perform an action when something changes.

    This is a view model for a shopping cart line item (properties such as qty, sku, description, price).

    // View Model for an item in my shopping cart
    var CartItemViewModel = function(data) 
    {
        // map all the properties
        // we could map manually if we want, but that's the whole point of
        // the mapping plugin that we don't need to
        ko.mapping.fromJS(data, {}, this);
    
        // subscribe to qty change
        this.qty.subscribe(function (newValue)
        {
            alert('qty now ' + this.qty());
            // UpdateCart()
    
        }, this);    
    
        // add computed observables if needed
        // ....
    }
    

    When you update (or create) your model using the mapping plugin you specify that for a property called 'items' each element in the array should be created with the 'create' function you specify.

        var mapping =
        {
            'items':
            {
                // map cart item 
                create: function (options)
                {
                    return new CartItemViewModel(options.data);
                }
            }
        };
    
        var data = ......  // get your data from somewhere
    
        // update the CartViewModel using the mapping rules
        ko.mapping.fromJS(data, mapping, rrvm.CartViewModel);
    
    0 讨论(0)
  • 提交回复
    热议问题