Ryan
Ryan

Reputation: 4414

Multiple <select /> chaining with KnockoutJS with dependencies stored in a database

I want to convert a solution of <select /> box chaining I've already built to use KnockoutJS. Here's how it works now:

I have a database that is full of products that have attributes and those have values which in turn have a dependency on another selected value.

product > attributes > values > dependency

bench > length > 42" > (height == 16")

In my database we also store what values are dependent on other values. e.g. length can only be 42" if the height is 16" or something like that.

This comes from the server to a JSON object on the client that contains all of the attributes, values and dependencies for the product in a tree like form.

var product = 
{
    attributes: 
    [
        values: 
        [
            value:
            {
                dependencies: [{dependencyOp}]
            }
        ]

    ]
};

I'll loop through each value and its dependency for the entire object and build an expression like "16 == 14 && 4 == 4" which would evaluate to false of course (14 being the selected value from another attribute). in that expression the && would be the dependencyOp in the dependencies array.

Now in my attempt I used KnockoutJS mapping plugin to get the object to be my view model but my problem is when I make a dependentObservable that needs to know what its dependant on. So now I would have to loop through every single array/object in my product variable?

Upvotes: 1

Views: 629

Answers (1)

Gene Golovchinsky
Gene Golovchinsky

Reputation: 6131

If I understood your question, you're trying to get data from your server, and use it determine if the user's input is valid. If that's the case, put your data structure into a field in your viewModel, and make your dependentObservable dependent on that field.

function ViewModel() {
    this.data = ko.observable();
    this.input = ko.observable();
    this.isValid = ko.dependentObservable(function() {
        // evaluate input() against data() to determine it is valid; return a boolean
        return ...;
    }, this);

    this.loadData = function() {
        $.ajax('/data/get', {
             success: function(dataFromServer) {
                 this.data(dataFromServer);
             });
    }
}

var vm = new ViewModel();
ko.applyBindings(vm);
vm.loadData();

now you can refer to this dependentObservable in a data-bind attribute like this

  <input type="text" data-bind="value: input, valueupdate='afterkeydown'" />
  <div data-bind="visible: isValid">shown only when data is valid...</div>

Upvotes: 2

Related Questions