挖空.js因变量选择

knockout.js dependent variable selects

本文关键字:选择 因变量 js 挖空      更新时间:2023-09-26

[ 请参阅底部的更新 ]

我正在尝试进行镂空依赖的选择,它旨在通过这些属性进行"产品"选择,例如产品可以具有"尺寸"和"材料",如果我选择"尺寸",则挖空脚本向后端发出请求并检索哪些"材料"可用于所选尺寸,换句话说,如果选择了属性, 过滤掉其他属性以仅显示可用值("所有大小":1,2,3,4,5;"铝":1,4)。

属性

列表是完全动态的,大约有80个属性可以任意链接到产品。

对于这种情况,是否有任何"最佳实践"?

我正在尝试用这样的代码来解决它,但还没有成功:

var ViewModel = function(data) {
    var self = this;
    self.data = data;
    self.attributes = ko.observableArray();
    self.data.forEach(function(item, i, a) {
        // I passed .self to catch it later
        // in products as view_model.attributes().
        self.attributes.push(new VariableProduct(item, self));
    })
};
var VariableProduct = function(item, view_model) {
    var self = this;
    self.attribute_name = ko.observable(item.name);
    self.attribute_value = ko.observable('--');
    // list of attribute values
    self.attribute_values = ko.computed(function() {
        var result = {};
        view_model.attributes().forEach(function(attribute, i, a) {
            // here I try to filter each attributes lists by values
            // it doesn't work well
            if (attribute.attribute_name() != self.attribute_name() && self.attribute_value() != '--') {
                result = attribute.attribute_values().filter(
                        function(value) {
                            return value.indexOf(self.attribute_value()) >= 0;
                        });
            }
        });
        return result;
    });
};

更新 1:通过 Dnyanesh 对 ko.subscribe() 的引用,我已经获得了这些结果,还不行,但是一个进步:

http://jsfiddle.net/xwild/65eq14p3/

更新 2:最后,它被用knockout.actor和knockout.mapping插件解决了。

相关的堆栈溢出问题,包括详细信息和答案。

对于依赖选择,我认为您可以通过以下方式使用订阅

var vm = {
        sizes: ko.observableArray([
            { name: 'size 1', id: 1},
            { name: 'size 2', id: 2},
            { name: 'size 3', id: 3},
            { name: 'size 4', id: 4}
        ]),
        selectedSize : ko.observable(0),
    
    };
        
          vm.selectedSize.subscribe(function(newValue){
              alert('Selected Size is ---> ' + newValue )
           // Here at this point call your ajax or backend method and bind the values which are coming form 
        });
      
    ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<select data-bind="
    options: sizes,
    optionsText: 'name',
    optionsValue: 'id',
    value: selectedSize,
    optionsCaption: 'Choose Size...'"">
</select>
 
<select data-bind="
    options: material,
    optionsText: 'name',
    optionsValue: 'id',
    value: selectedMaterial,
    optionsCaption: 'Choose Material...'"">
</select>

我知道我说的只是您问题的一部分解决方案,但是,我认为您需要划分数据对象以将其绑定到各种控件。