"Multi dimensional" JSON in javascript - javascript

I can create a jquery object inline like this (this code is working)
$('#tip').qtip({
content: el.REASON,
position: {
corner: {
target: 'rightMiddle',
tooltip: 'leftMiddle'
}
},
style: {
tip: {
corner: 'leftMiddle',
},
border: {
radius: 11,
width: 4
},
name: 'red'
},
show: {
ready: true,
effect: { type: 'slide' }
},
hide: {
when: { target: jq, event: 'click' },
effect: function() {
$(this).fadeTo(200, 0);
}
}
})
now I want to move this JSON to a function, because I have multiple constructors in my code (this code is not working)
function qtipJSON(el, jq) {
return
{
content: el.REASON,
position: {
corner: {
target: 'rightMiddle',
tooltip: 'leftMiddle'
}
},
style: {
tip: {
corner: 'leftMiddle',
},
border: {
radius: 11,
width: 4
},
name: 'red'
},
show: {
ready: true,
effect: { type: 'slide' }
},
hide: {
when: { target: jq, event: 'click' },
effect: function() {
$(this).fadeTo(200, 0);
}
}
}
};
$('#tip')(qtipJSON(el, qj))
My error is
Uncaught SyntaxError: Unexpected token {
I've noticed that it's because of nested jsons.
WORKING:
function a(){
return {sdasda:'asda',sdasd:'asdas'}
}
for(i in a()){
document.write(i)
}
ALSO WORKING:
function a(){
return {sdasda:'asda',sdasd:'asdas', aa:{sds:'1212', sddss:'2222'}}
}
for(i in a()){
document.write(i)
}

Replace this
return
{
content: el.REASON,
...
by this:
return {
content: el.REASON,
...
and welcome to the club of people injured by JS semicolon injection.

You cannot end a line with return if you want to return an object literal because of implicit semicolon injection.
By moving the opening left brace to the same line as the return it will work.
Here is a slight tweak of what you have: http://jsfiddle.net/FqCVD/ (I made some string literals to compensate for undefined variables).

The problem with your final example is a missing : after aa. It should be
return {sdasda:'asda',sdasd:'asdas', aa: {sds:'1212', sddss:'2222'}}
Your function function qtipJSON(el, jq) is missing a semicolon at the end of the return.
As others have mentioned, the problem is the 'return' keyword on a line by itself. When you have a problem like this one try JSLint. It would have reported this error.

javascript will assume you forgot a semi-column and give you this:
return {;
par: 'val'
});
Which won't work. What you should do is wrap your return value/object in parenthesis, like this:
return ({
par: 'val'
});

Related

variable amount of optional parameters

Im using this tool here http://craftpip.github.io/jquery-confirm/#dialog and i wanted to have a popup that has a variable amount of buttons based on a piece of data used to construct pop up.
Here is an example of what a very simple/empty one looks like.
$.confirm({
title: 'testing',
content: 'this has two static buttons',
buttons: {
confirm: function () {
},
cancel: function () {
},
}
});
What i want is to be able to put a foreach loop in side of "buttons: { ... }".
Is there a way to do so or a way to achieve what i am trying to do?
Just build your options object before :
var options = {
title: 'testing',
content: 'this has two static buttons',
buttons: {},
};
$.each( variable_name, function(){
options.buttons[ this.btn_name ] = this.fn;
} );
$.confirm( options );
Of course, everything depends on how the object you loop looks like, but the logic is here.
Your logic is inverted. The following is an object:
{
title: 'testing',
content: 'this has two static buttons',
buttons: {
confirm: function () {
},
cancel: function () {
},
}
}
So you could do:
var options = {
title: 'testing',
content: 'this has two static buttons',
buttons: {
confirm: function () {
},
cancel: function () {
},
}
};
$.confirm(options);
You then can add items by
options.buttons["mybutton"] = function() { };
You can place the previous code in a loop and change the string "mybutton" to whatever you want for whatever functions you have. You're basically asking how to add a property to and existing javascript object.

How to get golbal data in main.js file in Vue JS?

following code is from my main.js file. Here I am parsing data from a url using Vue object and it returns some array of data. Now, In the main.js file I have a another GraphChart object and here I need some data from tableData.
How it would be possible? or any other tricks ?
Now I am getting nothing.
var tableData = new Vue({
data: {
items: ''
},
methods: {
graphData: function () {
var self = this;
var testdata= '';
$.get( 'http://localhost:3000/db', function( data ) {
self.items = data;
});
},
},
created: function() {
this.graphData();
},
computed:{
});
new GraphChart('.graph', {
stroke: {
width: 24,
gap: 14
},
animation: {
duration: -1,
delay: -1
},
// series: needs data from ITEMS object
series:items._data.radialChart[1]
}
)
First, you would be able to get the data using tableData.items if you left the creation of the chart where it is. I expect there might be a problem with that though, because the data is retrieved asynchronously, meaning the chart will be created before the data is returned.
It looks like you will need to move the code that creates the chart into the callback that gets your data.
$.get("http://localhost:3000/db", function(data) {
self.items = data;
new GraphChart(".graph", {
stroke: {
width: 24,
gap: 14
},
animation: {
duration: -1,
delay: -1
},
series: self.items._data.radialChart[1]
});
});
Also, you could replace .graph with a Vue reference, but you didn't post your template, so I'm not sure where .graph appears in your template. You might also need to wrap the creation of GraphChart in $nextTick if you continue to use .graph, in which case the code would be
$.get("http://localhost:3000/db", function(data) {
self.items = data;
self.$nextTick(() => {
new GraphChart(".graph", {
stroke: {
width: 24,
gap: 14
},
animation: {
duration: -1,
delay: -1
},
series: self.items._data.radialChart[1]
});
});
});

Explain a piece of Jquery code

i have this code
function deleteNode(options) {
$.ajaxService({
url: 'http://localhost:1209/Pages/services.aspx/Page_load',
data: { servicename: 'deletenode', nodename:""},
LoaderConteiner: "#message",
onStartService: function () { $(".failed-message,.success-message").hide(); },
onEndService: function () {},
onResponse: function (response) {
switch (response.result) {
case "1":
$.pushMessage({ message: 'ok', messageClass: 'success-message', delay: 6000, container: '#changemessage' });
break;
default:
$.pushMessage({ message: 'error', messageClass: 'failed-message', delay: 8000, container: '#changemessage' });
}
}
});
}
and call this function
deleteNode({ target: this });
I have explain about this code
whats the Role of "options" and "target: this" ?
Options is the parameter of deleteNode.
By passing a construct like this { target: this } you are passing an object literal as parameter, where
'this' is the object context from where you called the deleteNode function.
Inside deleteNode you can call options.target... in you example.
Regards

Problem with applying jQuery to an element which has been created by jQuery

Here's my code:
$("#ticker-wrapper").rssfeed("http://news.hse.gov.uk/feed/", {
limit: 5,
linktarget: '_blank',
titletag: 'p',
snippet: false,
header: false,
date: false,
content: false
});
$('#js-news').ticker({
controls: false,
titleText: ''
});
Basically, a rssfeed is placed inside the wrapper, I then want .ticker to add a ticker effect to the items pulled through by the .rssfeed.
The problem seems to be that the .rssfeed creates the id #js-news (which is where I want to apply the .ticker). Then it seems the .ticker gets fired before #js-news has been created. Effectively it seems to be trying to apply .ticker to the element which hasn't yet been created which then results in nothing appearing.
I've been looking into jQuery .live() and I can get all the code working on a click command. But I need to create the rss feed and apply the ticker when the page loads. Not quite sure what to do?
------ Edit ------
ah ha!
Seems it works now I've moved the main .rssfeed bulk into the html (out of the .ready) and rewriting the ticker code:
var tickerTryCount = 0;
function addTicker() {
if (tickerTryCount < 5) {
if ($('#js-news').size() > 0) {
$('#js-news').ticker({
controls: false,
titleText: ''
});
} else {
tickerTryCount++;
setTimeout(addTicker, 1000);
}
}
}
Call the ticker() on ajaxStop()
$("#ticker-wrapper")
.rssfeed("http://news.hse.gov.uk/feed/", {
limit: 5,
linktarget: '_blank',
titletag: 'p',
snippet: false,
header: false,
date: false,
content: false
})
.ajaxStop(function() {
$('#js-news').ticker({controls: false, titleText: '' });
});
ah ha!
Seems it works now I've moved the main .rssfeed bulk into the html (out of the .ready) and rewriting the ticker code:
var tickerTryCount = 0;
function addTicker() {
if (tickerTryCount < 5) {
if ($('#js-news').size() > 0) {
$('#js-news').ticker({
controls: false,
titleText: ''
});
} else {
tickerTryCount++;
setTimeout(addTicker, 1000);
}
}
}

jquery unspecified error IE

So, IE is giving me issues, surprise, surprise...
I create a jquery dialog box (Div3) and then inside div3, i display a table (Div4). This works fine in firefox. However, in IE it is not displaying div 3, the popup window. Instead it returns the error "Unspecified error," and only displays div4, the table. Code is below...
I believe the error is somewhere in the else statement.
Any help is appreciated. Thanks!
function displayMid(count) {
var x = $("#Pid"+count).text();
var y = $("#PidSeries"+count).text();
//alert(x);
if (x == 0) {
return;
}
else if (y == null || y == " " || y == "") {
$("#inputDiv3").html("").dialog('destroy');
$("#inputDiv3").dialog({
title: 'You must add the Product before you can assign catalogs!!!',
width: 500,
modal: true,
resizable: false,
buttons: {
'Close': function() { $(this).dialog('close'); }
}
});
}
else {
$("#inputDiv3").dialog('destroy');
$("#inputDiv3").html('<div style="height:300px;overflow-y:scroll;"><div id="inputDiv4"></div></div>').dialog({
title: 'Catalog for ' + $("#PidTitle"+count).text(),
width: 500,
modal: true,
resizable: false,
open: $.get('content_backend_pub_pid.ashx', { cmd: 4, pid: x }, function(o) {
$("#inputDiv4").html(o);
}),
buttons: {
'Close': function() { $(this).dialog('close'); }
}
});
}
}
Not sure about this but I think you should wrap the ajax call for open: in a anonymous function.
open: function(){
$.get('content_backend_pub_pid.ashx', { cmd: 4, pid: x }, function(o) {
$("#inputDiv4").html(o);
});
},
Usually IE specifies a line number for the error. You have a lot going on in there, try breaking down each part into its own statement on a separate line. You can then throw in console logs between each line as well.
In general I like to create a new variable and assign that to the property, or create a new local function if the property is a function.
The issue seems to be in your open function. Maybe try wrapping that in an anonymous function like so:
$("#inputDiv3").html('<div style="height:300px;overflow-y:scroll;"><div id="inputDiv4"></div></div>').dialog({
title: 'Catalog for ' + $("#PidTitle"+count).text(),
width: 500,
modal: true,
resizable: false,
open: function() {
$.get('content_backend_pub_pid.ashx', { cmd: 4, pid: x }, function(o) {
$("#inputDiv4").html(o);
});
},
buttons: {
'Close': function() { $(this).dialog('close'); }
}
});
Otherwise, the "get" will fire immediately as opposed to when you actually open the dialog.

Categories