Using variables and functions in an object literal - javascript

I am trying to get the ckeip jquery plugin to parse the id of my textarea to my php file.
The plugin is activated by the class name of my textarea:
$('.ckeip_edit').ckeip({
And then data is passed to my php file with an object literal:
data: {
name1 : 'value1',
name2 : 'value2'
},
I need to use the id attribute of my textarea in one of these so tried:
data: {
name : 'value',
id : function(){this.getAttribute("id")}
},
But this doesn't seem to work.
Can I use variables in an object literal?

In this case you want a .each() and use this where needed inside to get an attribute from the current element for usage, like this:
$('.ckeip_edit').each(function() {
$(this).ckeip({
data: {
name : 'value',
id : this.id
},
//options...
});
});

That won't work because this refers to the data object. You need to save the jQuery object so you can use it inside the object later.
Try something like:
var textarea = $('.ckeip_edit');
textarea.ckeip({
data: {
name : 'value',
id : textarea[0].id;
}
});

Related

Add an array to a json object in extjs

I wish to have an attribute called idField in my json object. Now this attribute is either an array if it contains multiple elements or just an object if it contains one element. I wish to create such an attribute from the data in an extjs store. In essence if the store contains just one element I need to insert this idField 'object' in the json object otherwise I need to insert an 'array' called idField in the json object. Please advise as to how to do that.
EDIT:
My store has 2 columns namely 'name' and 'type' in its data. What I wish is that if it contains just one element then my object should look like this:
{
...
idField : {
name : ...
type : ...
}
}
If my store contains 2 rows then my object should look like this :
{
...
idField : [
{
name : ...
type : ...
},
{
name : ...
type : ...
}
]
}
Also I have to INSERT this idField attribute inside the object. There is no currect idField attribute yet in the object.
EDIT 2:
I received this object in the console when I wrote console.log(Ext.getStore("My_store_name").data)
To get the data from the EXT JS store
var data = Ext.getStore("Your_Store_Name").data
In my snippet below I am assuming that you like to get the values from field name called item.
var data = Ext.getStore("Your_Store_Name").data
//imagine your JSON where you need to store is in variable myJSON
if (data.items.length == 1){
myJSON.idField = {type: 'sometype', name: data.item[0]} }
else if (data.item.length > 1)
{ //make an array of JSON
var list = [];
for(var i = 0; i < data.item.length; i++)
{
list.push({type: 'sometype', name: data.item[i]})
}
myJSON.idField = list; //set the array
}

Access js object using variable

I'm not sure if I'm correct with topic title, so sorry about that.
I've got JS object '_buildings', which structure looks like this:
_buildings : {
laboratory : {
exist : false,
value : 1000,
},
office : {
exist : false,
value : 500,
},
}
Is it possible to access object somehow using this method:
var chain = 'laboratory'; //it could be 'office' or any other building name
var value = _buildings.chain.value;
Point is, I need to access object param while using variable in chain. Is it possible?
JSFiddle: http://jsfiddle.net/3k5anjjj/
yes, use square bracket notation
var x = _buildings[chain].value;
Updated fiddle: http://jsfiddle.net/3k5anjjj/1/

The JSON parsed into HTML, how objects are mapped to corresponding HTML?

For example, the following JSON:
{
"A" : [{
name : "admin",
email:"xxx#msn.com"
},{
name : "anly",
email:"xxx#msn.com"
}]
"B" : [{
name : "beta",
email:"xxx#msn.com"
},{
name : "b",
email:"xxx#msn.com"
}]
}
Html formatted as follows:
<ul>
<li>admin</li>
<li>anly</li>
<li>besta</li>
<li>bestb</li>
</ul>
How By clicking li, found to their corresponding object?
I think the method is:
1, by traversing JSON find, but this way is time-consuming, not simple
2, which is bound to the data key and index attributes above and through the key index to find, but if some of the more complex data structures, as too cumbersome, and do not know that there is no other better way to achieve it?
The above content is translated through Google, I do not know whether a clear description of my problem?
Here are two examples of what I wrote myself realized:
http://jsfiddle.net/18q41mfr/
It all depends on your requirements. How large will this JSON object be and how frequently will it change?
For small or constantly changing JSON objects, it might be just fine to do the method 1.
For large and constant JSON objects, go with method 2. A cleaner way to achieve method 2 that you've suggested is to make use of the Underscore.js values and groupBy method.
Merge all values in your object with the var merged = _.values(object)
Group by name var formatted = _.groupBy(merged, 'name');
Resulting JSON is such:
{
admin: {
name : "admin",
email:"xxx#msn.com"
},
anly: {
name : "anly",
email:"xxx#msn.com"
},
...
}
Use the following code to get the value in your onclick event function on your li element:
formatted[this.innerHTML].email
It seems that you're already using jQuery; you can simply stuff the object references into your HTML elements using .data().
Internally, an object reference map is maintained and the HTML element stores the reference key in a special property name.
var items = {
"type_a" : [{
name : "test",
color : "red"
},{
name : "test",
color : "blue"
}],
"type_b" : [{
name : "test",
color : "orange"
},{
name : "test",
color : "yellow"
}]
};
for (var i in items) {
for (var j = 0; j < items[i].length; j++) {
$('<li>', {text: items[i][j].name})
.data(items[i][j])
.appendTo('#items');
}
}
$("#items").on("click", "li", function() {
var obj = $(this).data();
$("#detaila").html('name:' + obj.name + '<br>color:' + obj.color + '<br>' );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul id="items"></ul>
<div id="detaila"></div>
<div id="detailb"></div>
Your second method is kind of good enough.
Maintain a global object myObjs for searching, whose keys are name and the values are object itself.
For each of the objects like:
var obj = {
name : "beta",
email:"xxx#msn.com"
}
myObjs[obj[name]] = obj; // If the name is not unique, add an id.
Then bind the key to the HTML element:
<li data-key="admin">admin</li>
When the element is clicked, find the key, query myObjs and find the obj. Something like (assume you are using jQuery):
$('ul').on('click', 'li', function() {
var $this = $(this);
var name = $this.data('key');
var obj = myObjs[name];
console.log(obj); // Here is your corresponding object.
});
Cons: extra memory
Pros: fast.

Access JSON values from variable

The click handler is accessing a data attribute on the element and setting a variable based on what is it, in this case 'option1'. I want to use the name of this variable to access a JSON object. But in the example it's returning 'undefined', as if it's looking for an array called 'thisOption'. How can I use this data attribute to bring back the correct JSON content?
// Note: thisOption returns "option1", which is correct.
jq = jQuery;
// Pass info
jq('.button').click( function() {
var thisOption = jq(this).data('name');
jq('#subscriptions .price').text(thisOption.monthly);
});
var option1 = {
"name" : "Super Pack",
"monthly" : "€10",
"yearly" : "€100",
"gift" : "Free €20 voucher"
};
If option1 is in the global scope then you can access it via the window object with a dynamic key:
jq('#subscriptions .price').text(window[thisOption].monthly);
The [] notation allows you to use variable property or key names.
You can access the option1 like below
jq('#subscriptions .price').text(window[thisOption].monthly);
Because option1 is in global scope, you can access it like window.option1. When option1 is a value of some variable, then you should access like window[thisOption]
I made some structure so we can see it clearly, you can also check it in jsfiddle.net
Heres the url: http://jsfiddle.net/8hTrr/3/
HTML
test
<div id="subscriptions">
<p class="price"></p>
</div>
JS
var option1 = {
"name" : "Super Pack",
"monthly" : "€10",
"yearly" : "€100",
"gift" : "Free €20 voucher"
};
jq = jQuery;
// Pass info
jq('.button').click( function() {
var thisOption = jq(this).data('option');
jq('#subscriptions .price').text(option1[thisOption]);
});

Call a javascript function dynamically

I have some functions defined inside a array like this.
checkInputType : function(sel){
alert($(sel).prop('type'));
},
checkSelect : function(el){
.......
},
.....
And I can call it like this options.checkInput($(this));. This is working.
Now I want to call any of those defined functions dynamically. So I have this array with the function names in it.
var elmType2Func = {'input' : 'checkInput', 'select' : 'checkSelect', 'textarea' : 'checkTextarea'};
Now looping through all elements inside a form I want to call the right function for each element(elmType2Func array with element as a key and function name as a value).
var element = $(this).prop('tagName').toLowerCase();
I cannot call like this - options.elmType2Func[element]($(this));
I know this is not the right way to call this function. Can anybody help me with this.
You need to store functions, not their names:
var elmType2Func = {'input' : checkInput, 'select' : checkSelect, 'textarea' : checkTextarea};
http://jsfiddle.net/hmb25/
If the functions are already members of some object, like:
var options = {
checkInput: function() {...},
checkSelect: function() {...},
}
then you can keep strings in elmType2Func:
var elmType2Func = {'input' : 'checkInput', 'select' : 'checkSelect', 'textarea' : 'checkTextarea'};
and use double indirection to refer to them:
var tag = $(this).prop('tagName').toLowerCase();
var fun = options[elmType2Func[tag]];
gives you a reference to the function.
Rather than putting a string for the name put the function
var elmType2Func = {
'input' : checkInput,
'select' : checkSelect,
'textarea' : checkTextarea,
'submit' : function (arg) { ... }
};
options.elmType2Func[element]($(this));
That is accessing the property with the literal name elmType2Func on the object - you want to use bracket notation here as well:
options[elmType2Func[element]]($(this));
Alternatively, you might not use elmType2Func as a property name lookup table, but to look up the functions directly:
var elmType2Func = {
'input' : options.checkInput,
'select' : options.checkSelect,
'textarea' : options.checkTextarea
};
elmType2Func[element]($(this));

Categories

Resources