Search code examples
javascriptjqueryobservablejsviewsdata-linking

JsObservable setting Property with Child Properties


How would I go about making an observable update to an object with child properties data-linked to form elements?

var app = {
    formData: {
        selectedThing: "thingValue1",
        selectedPlace: "placeValue1"
    }
};



$("#btnUpdate").on("click", function(){
    var replacementForm = {
        selectedThing: "thingValue2",
        selectedPlace: "placeValue2"
    }
    $.observable(app).setProperty("formData", replacementForm);
});

$("#content").link(true, app);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://www.jsviews.com/download/jsviews.js"></script>

<div id="content">
    <input data-link="formData.selectedThing trigger=true"/>
    <br/>
    <input data-link="formData.selectedPlace trigger=true"/>
</div>

<button id="btnUpdate" type="button">Update</button>

I have some input fields data-linked to properties of an object, and when the user presses a button, all of those fields need to get updated using an object (received from the server as JSON, deserialized into an object identical to the data object underlying the form elements.) Here is my jsfiddle: http://jsfiddle.net/xpe1ds0a/


Solution

  • Answer 'cloned' from https://stackoverflow.com/a/32339038/1054484

    The reason it is not working is because you are using a 'deep path' formData.selectedThing - which by default 'listens' to observable changes only at the leaf level, not deeper. To opt in to listening also to changes in the formData object, not just the leaf selectedThing property, you need to replace the . by ^ to indicate that you want to listen down to a deeper level in the path:

    <input data-link="formData.selectedThing trigger=true"/>
    <input data-link="formData.selectedPlace trigger=true"/>
    

    See the section Paths: leaf changes or deep changes in this documentation topic: http://www.jsviews.com/#observe.

    See also the examples such as Example: JsViews with plain objects and array in this topic: http://www.jsviews.com/#explore/objectsorvm.

    Updated jsfiddle here: http://jsfiddle.net/xpe1ds0a/1/