Reputation: 121
please help solve the problem. i make template, view and run them.
html:
<div class="space" id="space"></div>
tpl:
<script type="text/template" id="spaceTpl">
<div class="container main_container">
<div class="row">
gfdgdfgdfg<br>gfdgdfgdfg<br>gfdgdfgdfg<br>gfdgdfgdfg<br>gfdgdfgdfg<br>gfdgdfgdfg<br>gfdgdfgdfg<br>gfdgdfgdfg<br>
</div>
</div>
</script>
view:
window.APP = window.APP || {};
APP.SpaceView = Backbone.View.extend({
initialize: function() {
this.render();
},
template: _.template($('#spaceTpl').html()),
render: function() {
this.$el.html(this.template());
return this;
},
events: {
'click': 'move',
'keypress': 'move',
'keydown': 'move'
},
move: function(e) { console.log(222)
var code = e.keyCode || e.which;
if (code === 13) {
console.log('sdsd');
}
}
});
init:
var app = new APP.SpaceView({el: '#space'});
needed after press any key in console display '222'. but nothing happens.
i.e. keypress-handler is not worked. why??
https://jsfiddle.net/9t1cwfrv/16/
Upvotes: 0
Views: 96
Reputation: 3020
It works if you set it to use on a focused element. If you don't want to focus you can use it on body
element or document
.
Demo: https://jsfiddle.net/9t1cwfrv/21/
Upvotes: 1
Reputation: 2721
keypress
and keydown
will not work if the element is not focused.
It makes sense in an input, or you can try setting it up on the document element:
$(document).on('keypress', function(e){
var code = e.keyCode || e.which;
console.log(e, code);
});
Backbone input
example:
var Input = Backbone.View.extend({
tagName: 'input',
events: {
'keypress': 'press'
},
press: function(e){
var code = e.keyCode || e.which;
console.log( code );
}
});
(new Input()).$el.appendTo( document.body );
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.3/backbone-min.js'></script>
Upvotes: 0
Reputation: 670
in your template set tabindex="1"
<div class="container main_container" tabindex="1" >
https://jsfiddle.net/4ga489zy/1/
Upvotes: 1