How to capture the key event from a view? - javascript

I'm trying to capture the key event from a view as follows:
myView = Backbone.View.extend({
el: $('#someDiv'),
initialize: function(){
// initialize some subviews
},
render: function(){
return this;
},
events:{
'keypress #someDiv': 'showKey'
},
showKey: function(e){
console.log(e.keyCode);
}
})
That does not work ?
ps: There a no [input] elements in the view or its subviews. I just need to know if the user presses any key and then do something on the view.

You can do this in the view initialize() function:
_.bindAll(this, 'on_keypress');
$(document).bind('keypress', this.on_keypress);

Key pressed goes to the focused element on the page. If you have nothing in your view and the view does not have any focus, then you will not have any key press events.
( btw if you want to do key press event for this.el, do "keypress" : "showKey" )
In you above code the body will most likely receive all keypress events.

Related

keypress event does not triggered after choosing a choice from radio button

Using backbone js i want to execute a function while hitting on the ENTER Key.
I have a form :
When i enter a vallue in an input and hit enter, the function is triggered and works fine.
When i choose a button radio and hitting enter my function isn't called. Not OK
I am using this code in my view:
View.FormCustomer = CommonViews.FormCustomer.extend({
title : "Ajouter une fiche",
},
events: {
"keypress": "getKeyCode"
},
getKeyCode: function(e){
console.log(e.keyCode);
if(e.keyCode == "13"){
this.save(e);
}
},
Does any one have any suggestions?
You might have to listen to that keypress event at the document and not in your events object.
...
initialize: function(){
var _this = this;
$(document).on('keypress.namespace', function(){
_this.someMethod();
});
},
...
//you'll have to remove that event when you ditch your view, assuming you have already override your remove method...
remove: function(){
$(document).off('.namespace');
}

backbone.js events not bind to fire action on text area

I have a text area in my template .i want to pass text value from text area to function (view ) change event. I bound the "change" event to textarea but action is not working.
template
<div id="replyt" class="commentArea"> <textarea id="rep" class="form-control" placeholder="What's on your mind ?" rows="2"></textarea>
</div>
My view
var PostwallView = Backbone.View.extend({
el: $("#content"),
events: {
'change #rep': 'test',// or which event i need
},
My action
test:function(e)
{
var val = $(e.currentTarget).val();
alert( val );
e.preventDefault();
},
Here I used keyup and keydown. My event is working but action fire in first character when I am typing in text area
The input and keydown/up events are triggered when the value changes or a key is pressed. I don't know when you expect change to trigger, but blur triggers when the textarea loses focus:
'blur #rep': 'test'
"blur #rep":"yourMethod"
yourMethod:function(){
if($('#textArea').val() != null || '#textArea').val() != undefined){
/*Call your other function here*/
}
}

Selecting elements from a list with Backbone.js

Pretty general question here, let me know if you would like me to elaborate more. I have a list of elements, each rendered by a view. When an element is clicked, it is highlighted, and the view responsible for that element sends its model to a separate view which displays additional information related to that element.
I'm trying to implement functionality for a user to use the arrow keys to switch between elements, but I'm not sure how to do this.
Here is the code for my View:
var app = app || {};
app.EmployeeView = Backbone.View.extend({
tagName: 'li',
className: 'list-group-item',
template: _.template('<%= Name %>'),
render: function() {
var html = this.template(this.model.attributes);
this.$el.html(html);
},
events: {
"mouseover" : function() {
this.$el.addClass('highlighted');
},
"mouseout" : function() {
this.$el.removeClass('highlighted');
},
"click" : function() {
$('.selected').removeClass('selected');
this.$el.addClass('selected');
$(document).trigger('select', [this.model]);
},
},
});
Does anyone have any suggestions on how I can implement using arrow keys to trigger the appropriate view to forward its model?
I had a very similar feature to implement for my product. I have a list of images. The user clicks on one thumbnail and visualize the image full size. There, I also have a detail box showing info of the picture, and I wanted the user to use arrow keys to got through the pics while staying in the full size view. I also have "prev" and "next" buttons that should work the same. I think the result is clean and this is what I did:
SingleEntryView = Backbone.View.extend({
initialize : function() {
// Here I save a reference to the currentIndex by getting the index
// of the current model within the collection.
this.currentIndex = this.collection.indexOf(this.model);
// Important: here I attach the keydown event to the whole document,
// so that the user doesn't necessarily have to focus the view's
// element to use the arrows.
$document.on('keydown.singleEntry', this.onKeyDown.bind(this));
},
// Having attached the keydown event to document, there's no autocleaning.
// Overriding remove to detach the listener when the view goes away.
remove : function() {
$document.off('.singleEntry');
Backbone.View.prototype.remove.call(this);
},
// Keydown listener. Interested only in arrow keys.
onKeyDown : function(e) {
if (e.keyCode == 37) // left arrow
this.prev();
else if (e.keyCode == 39) // right arrow
this.next();
return true;
},
// Click events on the prev/next buttons (they behave == to the arrow keys)
events : {
'click #prev' : 'prev',
'click #next' : 'next'
},
// Handlers shared by both prev/next buttons and arrow keys.
// What is the current index? Go to the prev/next one.
// If we are at the start/end, wrap around and go to the last/first.
prev : function() {
this.goTo(this.currentIndex > 0 ? this.currentIndex - 1 : this.collection.length - 1);
return false;
},
next : function() {
this.goTo(this.currentIndex < this.collection.length - 1 ? this.currentIndex + 1 : 0);
return false;
},
goTo : function(i) {
this.model = this.collection.at(i);
this.currentIndex = i;
// App is my Router
App.navigate('app/boards/' + this.collection.id + '/entries/' + this.model.id, {
trigger: true
});
}
}

How to monitor change in input

How to monitor change in input in backbone?
In AngularJs
<div ng-controller="W3">
<input type="text" ng-model="val" >
<p>{{val}}</p>
</div>
I want that field value has been displayed in <p></p>.
You have to add it as an event on your view:
var MyView = Backbone.View.extend({
events: {
'keyup input': 'updateParagraph'
},
updateParagraph: function(ev) {
this.$('p').html(ev.target.value);
}
});
This assumes that your HTML for the view is just like what you have in your question. If you want to use multiple events, you will need to add each one to the hash. Like:
events: {
'keyup input': 'updateParagraph',
'propertychange input': 'updateParagraph',
// etc.
}
And if your view is tied to a model and the input should update the model, I would write it this way instead:
var MyView = Backbone.View.extend({
initialize: function() {
this.listenTo(this.model, 'change:text', this.updateParagraph);
},
events: {
'keyup input': 'updateModel'
},
updateModel: function(ev) {
var target = ev.target;
// Assuming that the input name is the model attribute
// To simplify, I'm just going to set something specific
this.model.set('text', target.value);
},
updateParagraph: function(model, value) {
// Set the input value as well, so it stays in sync
this.$('input').val(value);
this.$('p').html(value);
}
});
That makes it so that if you change that attribute on the model in any other view, the paragraph would still update, regardless of whether it was that input or not.

ExtJs manually firing Click event, button param is different from mouse click

So, I have a login controller, you can click login with mouse or press Enter key, like this:
Ext.define('My.controller.Login', {
extend: 'Ext.app.Controller',
init: function(application) {
this.control({
"#idLogin button": {click: this.onButton},
"#idLogin form > *": {specialkey: this.onKey}
});
},
onButton: function(button, e, eOpts) {
var win = button.up('window'); // the login window
//do more stuff...
},
onKey: function (field, el) {
if (el.getKey() == Ext.EventObject.ENTER) //ENTER key performs Login
Ext.getCmp('#idLogin button').fireEvent('click');
}
});
I realised when I use the mouse to click the Login button, onButton function works properly, button.up() returns me the Login window.
However, if I pressed Enter key and fires the onKey function to do fireEvent('click'), in this case the onButton fires up but parameter button NOT the same as the button parameter received when you click by mouse! And this time, button.up() function is undefined.
Question is, why does fireEvent('click') give me a different button parameter?
You must use the fireEvent function like that:
var myBtn = Ext.getCmp('#idLogin button');
myBtn.fireEvent('click', myBtn);
Give it a try.
Because the button click event is a synthetic event fired by the framework. It passes along the button instance and an event object. fireEvent means "notify any subscribers that this event has happened, with these arguments", not "trigger a click event on the underlying button".
So you'd need to use:
button.fireEvent('click', button);
However, this doesn't really make sense, you're just adding an extra layer of indirection.
Why not abstract it out:
Ext.define('My.controller.Login', {
extend: 'Ext.app.Controller',
init: function(application) {
this.control({
"#idLogin button": {click: this.onButton},
"#idLogin form > *": {specialkey: this.onKey}
});
},
onButton: function(button, e, eOpts) {
this.doWindowFoo();
},
onKey: function (field, el) {
if (el.getKey() == Ext.EventObject.ENTER) //ENTER key performs Login
this.doWindowFoo();
},
doWindowFoo: function() {
// Assumes the window has an id idLogin, there are several other ways to get a reference
var win = Ext.getCmp('idLogin');
}
});
Use:
var button= Ext.getCmp('#idLogin button');
button.fireHandler();
this will call the handler function in your button, in my case it worked, due i override that button handler with additional functionality and parameters value changes...(extjs 4.1.1)
Ext.getCmp('#idLogin button').handler();
A more general way:
document.querySelector("what-ever-el-selector").click();
Tested on extjs 4.2.6
Cheers

Categories

Resources