which is the best Javascript Keyboard event library.(Hotkeys,Shortcuts ) [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
i want to make a bbs forum that using much Keyboard event ,
so which is the best Keyboard event library,
thanks

Just another to throw in the mix. I recently released one called Mousetrap. You can check out examples at http://craig.is/killing/mice

Try KeyboardJS
its as simple as
KeyboardJS.on('a', function(){ alert('hello!'); });
yet as flexible as
var bindInstance = KeyboardJS.on('ctrl + a, ctrl + b, c', function(event, keysPressedArray, keyComboString){
//you get the event object
console.log('event object', event);
//you get the keys pressed array
console.log('keys pressed', keysPressedArray);
//you get the key combo string
console.log('combo pressed', keyComboString);
console.log('I will fire when \'ctrl + a\' or \'ctrl +b\' or \'c\' is pressed down');
//block event bubble
return false;
}, function(event, keysPressedArray, keyComboString) {
console.log('I will fire on key up');
//block event bubble
return false;
});
you can clear a binding by calling
bindInstance.clear();
you can clear all binds with specific keys with
KeyboardJS.clear('a, b');
Its open source and available on Github. Its comes in ether a global library or an AMD module for RequireJS.
Here's an introduction video.
There, now stop worrying about the keyboard and code your app. ;)

KEYPRESS is focused on game input and supports any key as a modifier, among other features. It's also pre-packaged for Meteor.

From what I have seen Mousetrap is the only library that let's you specify key sequences rather than combinations. This came in very handy for my application.

Lots of JavaScript libraries come replete with ways of capturing key input and using it to your advantage. It's a good bet that you will be able to find a library to do just that, and nothing else. I don't have a lot of experience there, however.
I've been using Ext for a while now, and their KeyMap class is really easy to work with. Here is a simple example using it.
new Ext.KeyMap(Ext.getDoc(), {
key: 'abc',
alt: true,
handler: function(k, e) {
var t = Ext.getCmp('tabpanel');
switch(k) {
case 65:
t.setActiveTab(0);
break;
case 66:
t.setActiveTab(1);
break;
case 67:
t.setActiveTab(2);
break;
}
},
stopEvent: true
});
This takes class, Ext.TabPanel, and allows the user to push a keyboard key to change tabs, rather than clicking the tabs themselves.
It can, of course, do much more than this. This is a simple example of how it works though.

This one is pretty good for jquery.
https://github.com/jeresig/jquery.hotkeys

This one is better if you are starting and if you want to understand how hot-keys work.
https://github.com/UthaiahBollera/HotkeysInJavascriptLibrary

You can try this one...
http://unixpapa.com/js/key.html

Related

Vuejs 2 + form validation [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
Since vue-validator https://github.com/vuejs/vue-validator is being ready for Vuejs 2, what is the best way to implement frontend validation?
UPDATE
I've found this awesome plugin
Vee Validate
In my opinion, a good way to implement front end validation for VueJS is to use vuelidate.
It's very simple to use and powerful. It offers model-base validation, it means that it's what you define in data that is validated, so it's totally decoupled from the templates. It comes with common built-in validators for email , min and max length or required. And many others.
Since it's all ultimately Javascript, you could also use some of the existing Javascript validation libraries like Parsely.js or Validate.js to hook this up. One thing that's nice about the Validate.js library is that it's format could easily be stored in the global store if you're using Vuex:
var constraints = {
creditCardNumber: {
presence: true,
format: {
pattern: /^(34|37|4|5[1-5]).*$/,
message: function(value, attribute, validatorOptions, attributes, globalOptions) {
return validate.format("^%{num} is not a valid credit card number", {
num: value
});
}
},
length: function(value, attributes, attributeName, options, constraints) {
if (value) {
// Amex
if ((/^(34|37).*$/).test(value)) return {is: 15};
// Visa, Mastercard
if ((/^(4|5[1-5]).*$/).test(value)) return {is: 16};
}
// Unknown card, don't validate length
return false;
}
},
creditCardZip: function(value, attributes, attributeName, options, constraints) {
if (!(/^(34|37).*$/).test(attributes.creditCardNumber)) return null;
return {
presence: {message: "is required when using AMEX"},
length: {is: 5}
};
}
};
Then used as such:
validate({creditCardNumber: "4"}, constraints);
// => {"creditCardNumber": ["Credit card number is the wrong length (should be 16 characters)"]}
validate({creditCardNumber: "9999999999999999"}, constraints);
// => {"creditCardNumber": ["9999999999999999 is not a valid credit card number"]}
validate({creditCardNumber: "4242424242424242"}, constraints);
// => undefined
validate({creditCardNumber: "340000000000000"}, constraints);
// => {"creditCardZip": ["Credit card zip is required when using AMEX"]}
You could also hook those validate() functions to your component with something along the lines of #blur=validate(...)
Currently there are not many choices. Take a look at vue-awesome where you can find the most relevant libraries. There are 2 at the moment.
If you are using semantic-ui or its an option for you they have an amazing form validation plugin.
semantic-ui-form-validation
I've used it with Vuejs and it works great.
I found this validator simple, flexible and well documented. It cover most scenarios of validating forms in Vue Js.
I used Jquery validator plugin in the past. Compared to that, this simple-vue-validator really stands out in its flexibility and its ability to validate both hard-coded and dynamically generated forms.
https://github.com/semisleep/simple-vue-validator
I used it extensively for my SaaS project and so far it has gone on really well.

Give a second name to a variable in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I have a code source that contains a long variable name (postCustomThumbnailsScrollerHeight).
I don't want to rename this variable for the whole code source so that I easily continue the project, but to have a shorthand of its name. I tried following solution (which works) at the first declaration of the variable, but I am not sure if it is the correct way to do so. I have a different color of d in IDE:
var postCustomThumbnailsScrollerHeight= d= $('.post-scroller').outerHeight();
I am seeking by this question your usual expert advice.
No, this isn't really correct: you're not declaring the d variable, only assigning to it, and thus
making it global (which may or not be desired)
making your code incompatible with strict mode
Here's a solution:
var d = $('.post-scroller').outerHeight(),
postCustomThumbnailsScrollerHeight = d;
Note that this should only be done for readability/typing issues, not for downloaded script size: minifiers should be used for that latter goal.
Be also careful that you're not making an alias, but really two variables. If you assign to one, you won't change the other one. It's hard to give a definite advice without more information but the usual solution is to have namespaced object:
Assuming you have a struct
myApp.thumbnailScrollers.postCustom = {height:...
then you would just assign that latter object to a local variable in a module or function:
var s = myApp.thumbnailScrollers.postCustom
In this case, changing s.height would also change myApp.thumbnailScrollers.postCustom.height.
Probably you have different color because in this case b it's global variable.
As for my opinion will be better to write all definitions on different lines:
var postCustomThumbnailsScrollerHeight = $('.post-scroller').outerHeight();
var d = postCustomThumbnailsScrollerHeight;
Although JavaScript doesn't natively support references, you can stimulate them using code such as this:
function d(){
return postCustomThumbnailsScrollerHeight;
}
Then just use d() everywhere. It's not very elegant, but as far as I know it's the only way to get a reference in JavaScript.
Do you have a problem declaring that var in the next line?
You could just do:
var postCustomThumbnailsScrollerHeight = $('.post-scroller').outerHeight();
var d = postCustomThumbnailsScrollerHeight;

Typed immutable objects in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I am trying organize data types in React Flux-like application. All my data objects are immutable, for collections I am using immutable.js, which is perfect library for that. But for typed objects i use my own classes. I don't think it is the best solution, but i need to somehow handle default values, internal consistency, validations of data, add methods to that objects etc.
Is there some library available for that purpose?
Do you use immutable.js collections also for that kind of objects? So you handle consistency of data, validations and other functionality somewhere else?
Or do you use plain classes for that?
Do you think that is good idea to have typed objects in React/Flux based application?
Here is example of what kind of objects i mean and simple example how I use it.
class Event extends MyImmutableLib {
constructor(plain) {
this.start = plain.start;
this.end = plain.end;
this.name = plain.name || "unnamed event"; // some default value
this.attendants = plain.attendants || [];
this.valid = plain.start < plain.end; // simple check of validity, I can also throw exception if it is needed
Object.freeze(this); // I use freeze to be sure I don't accidentally change the object
}
getDuration() {
return this.end - plain.start; // methods are sometimes useful
}
addAttendant(newPerson) {
return this.set("attendants", this.attendants.concat([newPerson])) //immutable edit, so I return new object
}
}
var someEvent = new Event({start: new Date("2015-02-29"), end: new Date("2012-02-30")}) //
var jsMeetup = someEvent.set("name", "9th Js Meetup, Brno")
var jsMeetup = jsMeetup.addAttendant("Joe");
console.log(jsMeetup.name, jsMeetup.getDuration())
The best would be some library with:
Typed objects - so I would have my data better organized.
Default values
Validations
Methods
Immutability specific functions

Which is the best way to validate the parameters received by a function [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Create: function (title, text, orientation, trigger, layout) {
$(this).attr
},
The trigger parameter must receive one of two very specific words: 'hover' or 'click' and I can't think of a good way to ease the implementation of this function.
I did think of some solutions:
I can try to validate the parameter once already inside in the function and return a 'console.info' right after breaking the execution in case a wrong parameter has been sent, informing the developer of his mistake
I could create a ENUM and provide it as an interface for the developer (which would still make the developer have to read it in order to use it properly)
Occurred me while typing this post that I could just set standard values for the options, hence they're optional.
I just don't know which one is the best approach in a situation like this. Can I assume that the developer that is willing to use the code MUST read the code to find the best way to implement it or (as I suppose) I should be concerned with validations like the ones I described? Also which one is the best?
Comparing straight up with strings is a common practice in javascript. ENUM-like structures, although easy to implement, are usually not very used because you either have to define your ENUM-like as globals or do something like:
application.enums.myObject.hover= 1;
application.enums.myObject.click= 2;
myObject= new application.constructors.MyObject();
myObject.create(title, text, orientation, application.enums.myObject.hover, layout)
In this manner only application is global, but typing application.enums.myObject is a pain.
How to handle the error:
Option 1: throw an exception:
Create: function (title, text, orientation, trigger, layout) {
if (trigger !== "hover" && trigger !== "click") {
throw "error: invalid parameter trigger";
}
},
This will crash your script unless you have a catch clause somewhere. In some cases crashing the party is better than not providing a way to know what is wrong. If you intend on catching these exceptions (instead of letting them just crash the script) I recommed doing it properly by making classes for your errors and such.
Option 2: Return null.
Create: function (title, text, orientation, trigger, layout) {
if (trigger !== "hover" && trigger !== "click") {
return null;
}
},
This approach works better if you are going to use the return value of the function. When debugging you will see "object has no property named X" error when trying to use the return value (or your value will be coerced into the "null" string if you use it as such).
Option 3: Quietly ignore the error and do nothing. Either your script will crash on its own or it will do nothing. Not recommended
Observations:
1 - do not use the console object in production code. It's not part of the standard and IE does not expose it to the web page unless you open the developer console
2 - do not start your function names with an upper case letter unless it's a function that should be called with the 'new' keyword (ie a constructor function).

Which strategy makes more sense in this jQuery plugin? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm making a jQuery plugin that displays alerts on the page. The plugin itself inserts the alert markup into the DOM. Since the jQuery way is to make everything return this to maintain chaining, I've run into an interesting issue I'd like feedback on. I'm trying to decide between the following two options.
Option One:
$("#content").alert('prepend', {type:'error', message:'This is an error'})
This looks pretty simple. An alert is prepended to the beginning of the #content DOM element. The problem is that it's unclear what is returned. It would make sense to return the alert element that was just created, but that kind of goes against the jQuery way.
Option Two:
$("<div>").alert({type:'error', message:'This is an error'}).prependTo("#content")
This way seems less clear and less intuitive, but it's more inline with the jQuery way of doing things, and it's clear what element is going to be returned.
So which options would you choose? My concern is that most users may not know that you can do $('<div>') to create a new element. On the other hand, I don't know of any well-known projects whose jQuery plugin methods return elements other than the elements they're invoked on, but perhaps there are. Thoughts?
I would just put it in the jQuery namespace (instead of on its prototype):
$.alert({type:'error', message:'This is an error'}).prependTo("#content");
In addition, you might consider asking for a selector/DOM node/jQuery object, instead of having the user prepend it themselves:
$.alert({
parent: '#content', // or $('#content') or document.getElementById('content')
type: 'error',
message: 'This is an error'
});
If your alert system is meant to be a popup-like or modal-like system, the user shouldn't have to specify a container. However, you can allow him to pass a container to insert your alertbox in:
$.alert({
type: 'error',
message: 'This is an error',
container: $(...) // Optional
});
It would return your plugin instance, or the alert container.
No, jQuery does not always return this. Chainability means only that you should return the instance itself if there's no result of your method.
For example, the clone() returns a new jQuery instance too; so there's nothing wrong with it. If you say "it's unclear", just document it, or rename the method to e.g. "$.fn.getAlert".
Yet, you must choose the signature of your method. The first option is like having a mandatory parameter for the container. If you like to make it optional, you might make the alert system a static method: $.createAlert(...) with an optional parameter.

Categories

Resources