Search code examples
jsviewscomputed-observable

JSViews computed observable linked to <select> not updating with .set()


I am trying to link a <select> box to a computed observable object in JSViews. The <select> updates fine when the depended upon variable changes. However when selecting a new value in the <select> box it does not trigger the set() function I defined. See https://jsfiddle.net/4y274h0L/3/

Template

<select>
    {{for options}}
        <option value="{{:#data}}" data-link="{:#data} selected{:~root.computedSelectedOption() == #data}"></option>
    {{/for}}
</select>

Computed observable

function privateComputedOption() {
    return vm.tempSelectedOption;
}

privateComputedOption.depends = ["~root.tempSelectedOption"];

privateComputedOption.set = function(val) {
    $.observable(vm).setProperty("tempSelectedOption", val);
    console.log(val);
};

Any help would be very welcome!


Solution

  • You didn't actually data-link the select to the computed observable. For two-way bindings it is the binding on the select that will call the setter when the user changes the drop-down selection.

    <select data-link="computedSelectedOption()">
      {{for options}}
        <option value="{{:#data}}"
         data-link="{:#data} selected{:~root.computedSelectedOption()==#data}">  
        </option>
      {{/for}}
    </select>
    
    {^{:computedSelectedOption()}}
    

    I updated the jsfiddle as above:

    https://jsfiddle.net/4y274h0L/4/

    See for example http://www.jsviews.com/#samples/form-els/array-binding.

    BTW in the next update of JsViews things will be simplified and you will not need to data-link to selected{:~root.computedSelectedOption()==#data}" on the options. Just the data-link on the select <select data-link="computedSelectedOption()"> will suffice.