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 change
or keydown
events on <input>
s for triggering observable changes to the data. Subsequently the HTML5 input
event became available, and was the preferred event for responding to any change in the <input>
value. Later versions of JsViews use the input
event.
Calling $('#title').val('Hello').change();
will raise a change
event, but will not raise the input
event.
You can instead raise the input
event directly, by using:
$('#title').val('Hello').trigger('input');
Alternatively you can set trigger to false
either 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 on blur
/change
, not on keydown
).