Reputation: 11876
I'm trying to replicate the 2-way data-binding example on the AngularJS website.
Here's my code (in JQuery parlance for brevity):
$('#model-textbox').on('keyup', function(){
//get value of text box
var text_box_str = $(this).val();
//add it to the view
$('#view-div').html(text_box_str);
});
It works as expected, but there seems to be some kind of delay from the time the key is released, to when the text is displayed. That delay does not happen on the AngularJS website example.
I have tried a 'keydown' event variation (which takes care of the delay), but it looks like the textbox value is not updated before the .val()
call (so I'm always one key press behind).
How can I achieve quick view updates using keyup
, keydown
, or any other method?
Upvotes: 1
Views: 612
Reputation: 1519
Bind on input
to get the immediate synchronization. https://developer.mozilla.org/en-US/docs/Web/Events/input
var $view = $('#view-div');
var ie9 = navigator.appVersion.indexOf("MSIE 9.")!=-1;
var event = ('oninput' in document.documentElement && !ie9) && 'input' || 'keypress';
$('#model-textbox').on(event, function(){
var $el = $(this);
if(event === 'keypress') {
setTimeout(function(){ $view.text($el.val()); },0);
} else {
$view.text($el.val());
}
});
Also, checkout out RivetsJS for a small library that supports this functionality outside of Angular. http://rivetsjs.com
Edit: Added event support check to take you back past IE9 (if you care about such things.)
Upvotes: 2
Reputation: 136
I don't see that much of a delay, but it may help if you cache the jquery objects (the bigger the DOM, the more this will help):
var $view = $('#view-div');
var $box = $('#model-textbox');
$box.on('keyup', function(){
//get value of text box
var text_box_str = $box.val();
//add it to the view
$view.html(text_box_str);
});
https://jsbin.com/ruxajowolo/edit?html,js,output
Upvotes: 0