I want to update input field externally (via jQuery) and I expect the associated object to be updated too, like I just typed the value into the input field by hand.
Here is my html:
<div id="content"></div>
<button id="btn">Put "Hello" in content.</button>
Here is my template:
<script id="myTmpl" type="text/x-jsrender">
<div><input type="text" id="title" data-link="{:Title trigger=true:}" /></div>
</script>
Here is my code:
<script type="text/javascript">
obj = { Title: 'Hey' }
var tmpl = $.templates('#myTmpl');
tmpl.link('#content', obj);
$('#btn').click(function() {
$('#title').val('Hello').change();
});
</script>
The thing is when I press the button, the value goes into the input field correctly but the object (obj) is not updated (when I'm watching it in the debugger). When I'm typing value directly in the input field, the object is updated correctly. What's the correct approach here.
An interesting thing is that it has been working correctly until I changed jsViews version from 0.9.71 to 1.0.7.
Here is a version with 0.9.71: https://jsfiddle.net/zhsmn1eg/ Here is a version with 1.0.7: https://jsfiddle.net/zhsmn1eg/1/
The difference in the behavior is because early versions listened to the
changeorkeydownevents on<input>s for triggering observable changes to the data. Subsequently the HTML5inputevent became available, and was the preferred event for responding to any change in the<input>value. Later versions of JsViews use theinputevent.Calling
$('#title').val('Hello').change();will raise achangeevent, but will not raise theinputevent.You can instead raise the
inputevent directly, by using:Alternatively you can set trigger to
falseeither globally or locally. The call to$('#title').val('Hello').change();will then trigger a data update. (But typing into the input will now only trigger a data update onblur/change, not onkeydown).