understanding jBox accessing properties in a array - javascript

I was just going through the code of jBox.js and came across the following snippet:
var appendImage = function(gallery, id, preload, open) {
if (jQuery('#jBox-image-' + gallery + '-' + id).length) return;
var image = jQuery('<div/>', {
id: 'jBox-image-' + gallery + '-' + id,
'class': 'jBox-image-container'
}).css({
backgroundImage: 'url(' + this.images[gallery][id].src + ')',
backgroundSize: this.options.imageSize,
opacity: (open ? 1 : 0),
zIndex: (preload ? 0 : this.imageZIndex++)
}).appendTo(this.content);
var text = jQuery('<div/>', {
id: 'jBox-image-label-' + gallery + '-' + id,
'class': 'jBox-image-label' + (open ? ' active' : '')
}).html(this.images[gallery][id].label).appendTo(this.imageLabel);
!open && !preload && image.animate({opacity: 1}, this.options.imageFade);
}.bind(this);
now my question is pertaining to a really complicated line of code that is trying to access a certain property in a array, i am talking about the below line of code:
this.images[gallery][id].src
what kind of an array is the above line really trying to access ? I have worked and accessed arrays like below:
var s = [{
a : 'name',
b : 'surname'
}];
val = s[0].a; // "name"
console.log(val);
But the syntax i have highlighted seems to have a extra bit of hierarchy. I am sorry, i am still a javascript novice and i am finding it hard to visualize how a array that gets accessed like below.
this.images[gallery][id].src
Would look like ? So well can somebody give me an example ? and explain ?
Thank you.

gallery, id might just be strings and you can use the following property accessor for those:
var gallery = 'galleryx',
id = 'idx';
var images = { 'galleryx': { 'idx': 2 } };
console.log(images[gallery][id]) // === 2

Related

understanding the chained data() function in Unslider.js

was just poking a plugin online called Unslider.js , a simple lightweight carousal plugin i am having a great difficulty understanding the following ine of code in the plugin :
me.data(key, instance).data('key', key);
now let me explain the context of this line , in the plugin the above line is preceded by the following lines of code :
$.fn.unslider = function(o) {
var len = this.length;
// Enable multiple-slider support
return this.each(function(index) {
// Cache a copy of $(this), so it
var me = $(this),
// if len less than 1 , the below line returns "Unslider"
// Else it returns Unslider-1 , Unslider-2 and so on ..
key = 'unslider' + (len > 1 ? '-' + ++index : '');
instance = (new Unslider).init(me, o);
I ran a few tests and found out about the below line ,
key = 'unslider' + (len > 1 ? '-' + ++index : '');
that, key returns 'slider', if len "is less then" 1 and if more than 1, then the results would look something like 'slider-1', 'slider-2' , 'slider-3' and so on .
The next line that is :
instance = (new Unslider).init(me, o);
is createing a new instance of Unslider and storing it in instance and after that .
init(me,o) function is executed where ,
me = $(this) and o is nothing but an object literal passed by the user to the plugin .
now i gave all the above explanation , so that everything is not out of context .
now i did go to the Jquery official docs and checked the usage of data().
i saw examples such as :
$( "body" ).data( "foo", 52 );
$( "body" ).data( "bar", { myType: "test", count: 40 } );
$( "body" ).data( { baz: [ 1, 2, 3 ] } );
$( "body" ).data( "foo" ); // 52
$( "body" ).data(); // { foo: 52, bar: { myType: "test", count: 40 }, baz: [ 1, 2, 3 ] }
These examples are quite cute to be honest, but somehow they don't help me understand what i want to .
So coming back to my question ,
me.data(key, instance).data('key', key);
What does the above line really Doing ?
EDIT ::
and if i take off that line everything seems to be working just fine , the plugin still works fine and the carousal still slides .
thank you.
Alexander.
When jQuery's data is used with two arguements, a key and a value, it stores the value under the given key in an internal object that jQuery keeps track of.
When doing this, jQuery returns the collection, so it can be chained again
var me = $('#element'); // a DOM element
var me2 = me.data('key1', 'value'); // returns same DOM element
me2.data('key2', 'value');
is the same as
var me = $('#element'); // a DOM element
me.data('key1', 'value').data('key2', 'value');
because the collection is returned, and can be chained.
As for the data stored in data, that's something used internally by the plugin, and could be anything, even an object, as long as there's a key to get the data back again, remember this isn't data attributes in HTML, it's an internal store that accepts any data type, even an instance of a function.
As for the key, it just increments to be unique
key = 'unslider' + (len > 1 ? '-' + ++index : ''); // the string "unslider-1" etc
Then the first call to data stores the current instance of the slider
me.data(key, instance).data('key', key);
while the second one stores the key, as it's easier to just do
me.data('key');
to get the key back, if you don't know what the last number in the key is, so it's actually a little clever as it lets you do
var key = me.data('key');
var instance = me.data(key);
and get the correct intance back regardless of the index, increments etc.

Getting data from dynamic mongodb embedded object node.js

I have a mongoDB structure that looks like this:
values : { [
oneValue : {
number: '20'
unit: 'g'
}
differentValue : {
number : '30'
unit : 'g'
}
]}
I am using node js this is what I do:
doc.values.forEach(function(err, idx) {
var object = doc.values[idx];
}
And what ends up happening is I can get an object that looks like this:
object = oneValue : {
number: '20'
unit: 'g'
}
But node does not recognize it as a JSON because when I try to do JSON.parse(object) it doesn't know how to handle it.
I want to be able to get at the number field dynamically. So I don't want to say doc.values[idx].oneValue because this is a pretend case and in the real case oneValue could be one of 1000 different things. Does anyone know how I can access the 'number' field with this structure?
figured it out...
after
var object = docs.values[idx]
do this:
var objAsJson = JSON.stringify(object);
JSON.parse(objAsJson, function(k, v) {
console.log(k + " " + v);
});
That will print out all the data in the embedded object and you don't have to know the name.

Insert correct arrays doesn't work

Well, now i am getting "has to be an array", before it had to be a string.
Can someone help me out of this problem? Check comments.
function publishPhoto() {
var tags = []; var x,y=0;
if ( harBilled == 0 ) {
if ( profilSendt==0) {
var c =0;
//Get the online friends from array!
for ( i=0;i<globalTags.length;i++){
if ( c < 49 ){ //max 50 tags!
tags.push({"tag_uid": ""+globalTags[i]+"",
"x" : ""+(Math.floor(Math.random() * 309) + 1)+"",
"y" : ""+(Math.floor(Math.random() * 309) + 1)+""
});
}
c = c+1;
}
var newJson = new String(array2json(tags));
newJson = newJson.toString();
FB.api('me/photos', 'post', {
message: txt2send,
status: 'success',
url: 'http://meedies.com/0bcf1f22_smush_400x400.jpeg',
}, function (response) {
if (!response || response.error) {
harBilled=0;
alert(var_dump(response.error));
} else {
var fi = response.id;
alert("Now this!");
FB.api(fi + '/tags?tags='+tags, 'POST', function(response){
alert(var_dump(response));
});
harBilled=1;
//getPages()
}
})
profilSendt=1;
}
}
I am trying to insert multiple ids to be tagged on a picture. Can something help me though this correctly
Sounds like you're filling the wrong type of data into the tags array.
Try this...
var tags = [
{"tag_uid": 91839404, "x": 250,"y": 350},
{"tag_uid": 91839401, "x": 220,"y": 340}
];
Edit
Just insert the objects itself and not an array with one single object.
tags.push({"tag_uid": 91839404, "x": 250,"y": 350});
This is the Facebook definition:
PHOTO_ID/tags?tags=[{"id":"1234", "X":1, "y":2}, {"id":"12345", "x":1, "y":2}]
I've just tried to do that with json_encode. The result was:
[{"id":"1","x":"1","y":"2"},{"id":"2","x":"1","y":"2"}]
To post your variable tags, use
console.log(tags);
Doesn't work on old IE browsers.
It's still an array. If the api requires it as string, you'll have to encode it. Like I said, json encoding would return exactly the same "visual" result, except - it would be a string, not an array.
[{"tag_uid": 587908880,"x" : 17,"y" : 251},{"tag_uid": 664099777,"x" : 166,"y" : 197},{"tag_uid": 824600788,"x" : 275,"y" : 89},{"tag_uid": 1012286173,"x" : 247,"y" : 225},{"tag_uid": 1027953684,"x" : 81,"y" : 25},{"tag_uid": 1049653245,"x" : 169,"y" : 2},{"tag_uid": 1089472771,"x" : 236,"y" : 125},{"tag_uid": 1157692807,"x" : 75,"y" : 70},{"tag_uid": 1183641328,"x" : 307,"y" : 254},{"tag_uid": 1206853982,"x" : 154,"y" : 254},{"tag_uid": 1279891790,"x" : 54,"y" : 5},{"tag_uid": 1379771663,"x" : 206,"y" : 280},{"tag_uid": 1446366514,"x" : 37,"y" : 168},{"tag_uid": 1599969496,"x" : 26,"y" : 226},{"tag_uid": 1645141964,"x" : 250,"y" : 23},{"tag_uid": 100000830101385,"x" : 5,"y" : 110},{"tag_uid": 100003711738950,"x" : 174,"y" : 294},{"tag_uid": 100003908889022,"x" : 249,"y" : 38}]
Once the string is formated, you may send it this way:
PHOTO_ID/tags?tags=[{"id":"1234"}, {"id":"12345"}]
Here, you're converting your array to json (I'll assume it's converted correctly)
var newJson = new String(array2json(tags));
newJson = newJson.toString();
But here, you're still using the array
FB.api(fi + '/tags?tags='+tags
I think i've found your problem:
The x and y coordinates that you're using, should be as percentage offset from the left(x) and top(y). Allowed values are 0 - 100. As of your posts below, I see that some of the coordinates exceed the 100 limit. You should probably recalculate your coordinates as relative offsets. But for first, try it with some test data, to see if it works.
Also, see documentation.
Try this, a tell me, how it's gone.

Current object property as value in same object different property

Sorry for such a random title, but have no idea how to explain it better. And therefore, no idea if this is a duplicate question or not.
So, when declaring a new object, I'm looking to calculate the giga value:
var myObject = {
super : 1,
mega : 5,
uber : 100,
giga : this.super + this.mega + this.uber // super + mega + uber doesn't cut it either..
};
But this doesn't work, so, any ways of doing this while declaring, or not possible?
Hope I've made myself clear and thanks in advance!
In Javascript 1.5 you can use the get keyword to define a getter
var obj = {
super : 1,
mega : 5,
uber : 100,
get giga() {
return this.super + this.mega + this.uber;
}
};
alert(obj.giga) // 106
more on this http://robertnyman.com/2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/
I assume you have a really good reason for the need to do this inline, otherwise such
trickery is not really a good idea.
Here is what I came up with:
var myObject = (function(){
this.giga = this.super + this.mega + this.uber;
return this;
}).call({
super : 1,
mega : 5,
uber : 100
});
var myObject = {
super : 1,
mega : 5,
uber : 100
};
myObject.giga = myObject.super + myObject.mega + myObject.uber;

Dynamically adding members to a javascript object

I'm working on a scoring script for contract bridge, just for giggles. I'm storing the game as an object:
var game = {
team1 : { player1 : prompt("Team 1, first player: "), player2 : prompt("Team 1, second player:") },
team2 : { player1 : prompt("Team 2, first player: "), player2 : prompt("Team 2, second player:") },
}
function deal(bid){
console.log("The bid was " + bid);
game.hand = {"bid" : bid , "made" : undefined};
score();
}
So what I'd like to do though, better than this, is to keep a history of the games played this session. I'd like to, in pseudocode, do something like this:
game.(hand + (hand.length+1))
or something kind of like that; basically auto-increment a certain object within an object. I'm not so sure an array would would here, but perhaps? I'm open to suggestions/bettering of my code.
PS - I'd prefer to do this in javascript, not jQuery, Prototype, Dojo, MooTools... or any other library. Thanks!
EDIT
Sorry, let me clarify: The result after playing 3 hands or so would be an object like this:
var game = {
team1 : { player1 : prompt("Team 1, first player: "), player2 : prompt("Team 1, second player:") },
team2 : { player1 : prompt("Team 2, first player: "), player2 : prompt("Team 2, second player:") },
hand1 : { bid : 2 , made : 2 } ,
hand2 : { bid : 1 , made : 4 } ,
hand3 : { bid : 3 , made : 1 } ,
hand4 : { bid : 2 , //and made hasn't been set yet because we're mid-hand
}
Given your pseudocode, you can do the following:
game[hand + (hand.length+1)]
i.e. game["prop"] == game.prop - both provide access to the same property.
Old question, I see but I have a need to do something similar. I'd vote up the answer but I'm not allowed.
It appears the fastest way to do this is to access the object like a hash / associative array.
var d = {};
var z = "hand";
d[z+1] = "foo";
console.log(d.hand1);
Test this out in firebug. Seems to work pretty well.
JS does not seem to have an php equivalent to force resolution of the variables as in the curley braces around an expression.
d->{z+1} = "foo"; // can't find anything like this in JS.
Hope that helps,

Categories

Resources