I have the following utility function that works (obviously it only looks for 5 types of controls, but that's all I use):
util.getKendoControlType = function(controlId) {
let controlTypes = ['kendoAutoComplete','kendoMultiSelect','kendoDatePicker','kendoDropDownList','kendoNumericTextBox'];
for(let i = 0; i < controlTypes.length; i++) {
let control = $('#' + controlId).data(controlTypes[i]);
if (typeof(control) !== 'undefined' && control !== null) {
return controlTypes[i];
}
}
return null;
};
My question: is this the only way to get the control type of a Kendo UI control, or is there a better way?
(Note: I'm aware that instead of returning null, I could also throw an error.)
Sure! Use kendo.widgetInstance:
util.getKendoControlType = function(controlId) {
return kendo.widgetInstance($(`#${controlId}`)).options.name;
}
You can also get the role data attribute:
util.getKendoControlType = function(controlId) {
return $(`#${controlId}`).data('role');
}
Related
I am looking for a way to get all the attributes of an element that begins with "on" using jQuery or Vanilla JS. I am currently getting all attributes and then looping through them to get the ones I want using the method proposed by #primvdb on this post: Get all attributes of an element using jQuery.
My code looks like this:
/* Expanding .attr as proposed by #primvdb */
(function(old) {
$.fn.attr = function() {
if(arguments.length === 0) {
if(this.length === 0) {
return null;
}
var obj = {};
$.each(this[0].attributes, function() {
if(this.specified) {
obj[this.name] = this.value;
}
});
return obj;
}
return old.apply(this, arguments);
};
})($.fn.attr);
/* And then my function */
$.fn.attrThatBeginWith = function(begins){
var attributes = this.attr();
var attrThatBegin = {};
for(var attr in attributes){
if(attr.indexOf(begins)==0){
attrThatBegin[attr] = attributes[attr];
}
}
return attrThatBegin;
};
/* Usage */
var onAttributes = $("#MyElement").attrThatBeginWith("on");
And this works but is very "dirty". It's seems like with all the vast features of jQuery there should be a better "cleaner" way to do this. Does anybody have any suggestions?
You can get all attributes attached to an element with element.attributes.
The native attributes object can be converted to an array and then filtered based on the given string.
A plugin that does the above would look like
$.fn.attrThatBeginWith = function(begins){
return [].slice.call(this.get(0).attributes).filter(function(attr) {
return attr && attr.name && attr.name.indexOf(begins) === 0
});
};
FIDDLE
I have some JSON:
[{
"cityid":101,
"city":"Alta"
},
{
"cityid":102,
"city":"Bluffdale"
},
{
"cityid":105,
"city":"Draper"
},
{
"cityid":107,
"city":"Holladay"
}]
I can successfully search this array, and get the "city" value, with this function:
function getLocality(cid){
var storedlist = localStorage.getItem("citylist");
var clist = JSON.parse(storedlist);
for(var i = 0; i < clist.length; i++)
{
if(clist[i].cityid == cid) {
return clist[i].city;
} else {
}
}
}
My Issue:
When I try to use another function to get the city, instead of getting the cityid, it does not work.
The function I am using to try and get the city id, is as follows:
function getCityid(cid){
var storedlist = localStorage.getItem("citylist");
var clist = JSON.parse(storedlist);
for(var i = 0; i < clist.length; i++)
{
if(clist[i].city == cid) {
return clist[i].cityid;
} else {
}
}
}
I am calling the function as so:
getCityid('Draper');
I just opened up the console and tried both of your functions and they both seem to work. Since you didn't provide any sample input/output of your issue, I'll recommend the following:
Verify that you're passing in correct parameters into each function. The getLocality() should take in a cityid and getCityid() should take in a city.
Refrain from using == in javascript as this operator performs type coercion wherein things which are disparate types are "forced" to be the same type in order to perform comparison. You should instead use the === operator which will not perform type coercion. If the two things being compared are different types, it will simply evaluate to false.
Try this.
function getCityid(city) {
var storedlist = localStorage.getItem("citylist");
var clist = JSON.parse(storedlist);
for(var i = 0; i < clist.length; i++){
if(clist[i].city === city) {
return clist[i].cityid;
}
}
}
Explanation:
As a personal project, I'm trying to create my own lightweight version of Dependency Injection for JavaScript - Some would probably disagree with calling this DI because it has no interfaces, but I arrived at the conclusion that interfaces were overkill in JS since we can so easily type check. I have looked at the source of Angular, but I just feel like the complexity there may be overkill for my projects, and I'm interested in attempting my own for a learning experience anyway.
Question:
My question is, fundamentally, is the syntax I'm trying to implement impossible or not?
I'll explain my goal for the syntax, then provide the error and code snippet, and below that I'll post the full code.
Goal for Syntax:
I'd like the creation of a component, and injection of dependencies to work like this, where everything is a component, and anything can be a dependency. I created scope with a string path, using "/scopeName/subScopeName:componentName" to select a scope, so that code users can select the scope while defining the component in a simple way, using a ":" to select a component from the scope.
var JHTML = new Viziion('JHTML');
JHTML.addScope('/generate');
/* ...snip - see full code for the process component - snip ... */
JHTML.addComponent('/generate:init', function (jsonInput, process) {
var html = process(jsonInput);
return html;
}).inject([null, '/generate:process']);
The inject function just takes an array of component paths in the order the component's arguments are expected. null can be used to skip, allowing direct argument input instead, as shown above.
I also have something I call hooks, which are components stored in a certain place, and then there's a function returnUserHandle which will return an object consisting of just the hooks, so all of the functions are hidden in closures, and you can feed the code user just the usable methods, clean and easy, and can produce the final product as a library without the wiring, no need for my DI framework as a dependency. Hopefully that makes sense.
Error:
Right now, running the code (which is a very simple library to generate HTML by parsing a JSON structure) I get the error that process is undefined in the line var html = process(jsonInput);. I was having trouble understanding whether this is a fundamental design problem, or just a bug. Maybe this syntax is not possible, I'm hoping you can tell me.
Code:
Here's the code, and a link to the JS Bin.
/* Dependency Injection Framework - viziion.js */
function Viziion(appName) {
if (typeof appName == 'string') {
var that = this;
this.name = appName;
this.focus = null;
this.scope = {
'/': {
'subScopes': {},
'components': {}
}
};
this.hooks = {};
this.addScope = function(scopeName) {
if (typeof scopeName == 'string') {
var scopeArray = scopeName.split('/');
var scope = that.scope['/'];
for (var i = 0; i < scopeArray.length; i++) {
if (scopeArray[i] !== "") {
if (scope.subScopes[scopeArray[i]]) {
scope = scope.subScopes[scopeArray[i]];
} else {
scope.subScopes[scopeArray[i]] = {
'subScopes': {},
'components': {}
};
}
}
}
} else {
throw 'Scope path must be a string.';
}
return that;
};
this.addComponent = function(componentName, func) {
if (typeof componentName == 'string') {
var scopeArray = componentName.split(':');
if (scopeArray.length == 2) {
var scope = that.scope['/'];
var scopeName = scopeArray[1];
scopeArray = scopeArray[0].split('/');
for (var i = 0; i < scopeArray.length; i++) {
if (scopeArray[i] !== "") {
if ((i + 1) === scopeArray.length) {
scope.components[scopeName] = func;
that.focus = scope.components[scopeName];
} else if (scope.subScopes[scopeArray[i]]) {
scope = scope.subScopes[scopeArray[i]];
} else {
throw 'Scope path is invalid.';
}
}
}
} else {
throw 'Path does not include a component.';
}
} else {
throw 'Component path must be a string1.';
}
return that;
};
this.returnComponent = function(componentName, callback) {
if (typeof componentName == 'string') {
var scopeArray = componentName.split(':');
if (scopeArray.length == 2) {
var scope = that.scope['/'];
var scopeName = scopeArray[1];
scopeArray = scopeArray[0].split('/');
for (var i = 0; i < scopeArray.length; i++) {
if (scopeArray[i] !== "") {
if ((i + 1) === scopeArray.length) {
//console.log('yep1');
//console.log(scope.components[scopeName]);
callback(scope.components[scopeName]);
} else if (scope.subScopes[scopeArray[i]]) {
scope = scope.subScopes[scopeArray[i]];
} else {
throw 'Scope path is invalid.';
}
}
}
} else {
throw 'Path does not include a component.';
}
} else {
throw 'Component path must be a string2.';
}
};
this.addHook = function(hookName, func) {
if (typeof hookName == 'string') {
that.hooks[hookName] = func;
that.focus = that.hooks[hookName];
} else {
throw 'Hook name must be a string.';
}
return that;
};
this.inject = function(dependencyArray) {
if (dependencyArray) {
var args = [];
for (var i = 0; i < dependencyArray.length; i++) {
if (dependencyArray[i] !== null) {
that.returnComponent(dependencyArray[i], function(dependency) {
args.push(dependency);
});
}
}
console.log(that.focus);
that.focus.apply(null, args);
return that;
}
};
this.returnUserHandle = function() {
return that.hooks;
};
} else {
throw 'Viziion name must be a string.';
}
}
/* JSON HTML Generator - A Simple Library Using Viziion */
var JHTML = new Viziion('JHTML');
JHTML.addScope('/generate');
JHTML.addComponent('/generate:process', function(children) {
var html = [];
var loop = function() {
for (var i = 0; i < children.length; i++) {
if (children[i].tag) {
html.push('<' + tag + '>');
if (children[i].children) {
loop();
}
html.push('</' + tag + '>');
return html;
} else {
throw '[JHTML] Bad syntax: Tag type is not defined on node.';
}
}
};
}).inject();
JHTML.addComponent('/generate:init', function(jsonInput, process) {
console.log(process);
var html = process(jsonInput);
return html;
}).inject([null, '/generate:process']);
JHTML.addHook('generate', function(jsonInput, init) {
var html = init(jsonInput);
return html;
}).inject([null, '/generate:init']);
handle = JHTML.returnUserHandle();
/* HTML Generator Syntax - Client */
var htmlChunk = [{
tag: '!DOCTYPEHTML'
}, {
tag: 'html',
children: [{
tag: 'head',
children: []
}, {
tag: 'body',
children: []
}]
}];
console.log(handle.generate(htmlChunk));
is the syntax I'm trying to implement impossible or not?
It's absolutely possible, and I'm sure with a bit of bugfixing it'd work just fine.
What you're describing is essentially the same as Asynchronous Module Definition (AMD) which is used extensively for handling code dependencies.
Rather than continuing to pursue your own version of the same concept, I recommend that you give requirejs a try and follow the existing standards with your projects.
I'm trying to store a reference in my javascript to a page element that will be interacted with frequently and using this code:
var breadcrumbBar = null;
function getBreadcrumbBarElement() {
if (breadcrumbBar === null) {
breadcrumbBar = document.getElementById(breadcrumbBarElementId);
}
return breadcrumbBar;
}
However, I'm wondering if I can be more terse or idiomatic than this (and as a result improve my javascript more generally...)?
The idiomatic way is to use the logical or operator:
var breadcrumbBar = null;
function getBreadcrumbBarElement() {
return breadcrumbBar || (breadcrumbBar = document.getElementById(breadcrumbBarElementId));
}
or, to make this a bit more generic:
var elementCache = {}
function getCached(id) {
return elementCache[id] || (elementCache[id] = document.getElementById(id));
}
Or in order to encapsulate the cache into function:
function getCached(id) {
if (!getCached.elementCache) getCached.elementCache = {};
return getCached.elementCache[id] || (getCached.elementCache[id] = document.getElementById(id));
}
Hey I tried this code for my project and it returns some bad results. getting the last Id does not work properly .
function regionDropDownChanged() {
var selectedRegionId = getRegionDropDown();
if (selectedRegionId !== null) {
var val = selectedRegionId[selectedRegionId.length - 1];
alert(val);
} else return;
$.get("/Common/JsonFunction/GetEnterprisesOfRegion", { regionId: val }, function (fields) {
fillDropDown(fields, getEnterpriseDropDown());
enableEnterpriseDropDown();
});
}
Also enableEnterpriseDropDown() Dropdown does not work after selecting IDs.
function enableEnterpriseDropDown() {
var enterpriseDropDown = getEnterpriseDropDown();
$(enterpriseDropDown).prop('disabled', false);
}
other methods that I use in my project
function getRegionDropDown() {
var dropDown = $("#RegionId").val();
return dropDown;
}
function getEnterpriseDropDown() {
var dropDown = $("#EnterpriseId");
return dropDown;
}
remember that I use Choosen Plugin.
Here you are using array of selectedRegionId but it is a value, as you have called getRegionDropDown() which returns a single value.
var selectedRegionId = getRegionDropDown();
So,
you may get undefined in alert in these lines
var val = selectedRegionId[selectedRegionId.length - 1];
alert(val);
If you create a Fiddle then it would be better to solve you problem.