jQuery calling a variable that has variable inside a function - javascript

I have written my javascript too much, and now the code keeps repeating itself, whereas I lack of knowledge on how to simplify matters. I have this idea of calling variable into function, but I don't know how to call this kind of function that contains dynamic variables.
Anyone got any tips on how can I achieve this?
var container = '#content_container';
function container_load(){
var data = $(this).attr('data');
var dataObject = {command : data};
var title = '<h2 data="'+dataObject.command+'">'+
dataObject.command+'</h2>';
};
$(function(){
$('nav')on.('click', 'a', function(){
container_load();
$(container).prepend(title);
});
});
Apparently, console returned ReferenceError: Can't find variable: dataObject

There is two issue is in your code
var container = '#content_container';
var title; //title should be declare as global,same as "container" variable
function container_load(dis){
var data = dis.attr('data');
var dataObject = {command : data};
title = '<h2 data="'+dataObject.command+'">'+
dataObject.command+'</h2>';
}
$(function(){
$('nav').on('click', 'a', function(){
container_load($(this)); //you have to pass the current element
$(container).prepend(title);
});
});
Demo : Demo

Try this :
var container = '#content_container';
function container_load(currElementId){
var data = $("#"+currElementId).attr('data');
return '<h2 data="'+data+'">'+data+'</h2>';
};
$(function(){
$('nav')on.('click', 'a', function(){
var title = container_load(this.id);
$(container).prepend(title);
});
});
Here your problem is that you cannot 'this' in other function for that you need to pass it from your current function.

There seems to be few mistakes in your code, The scope is wrong and the data attribute is used not correctly I presume. I suppose this is what you wanted http://jsfiddle.net/EjEqK/2/
HTML
<nav >aaa</nav>
<div id="content_container"></div>
JS
function container_load() {
var data = $(this).data("val");
var dataObject = { command: data };
$("#content_container").prepend('<h2 data-val="' + dataObject.command + '">' + dataObject.command + '</h2>');
};
$(function () { $('nav > a').on('click', container_load); });
PS: If you don't need dataObject for anything else, directly use data

I think this will help you :
function container_load(currElement){
var data = $(currElement).attr('data');
return '<h2 data="'+data+'">'+data+'</h2>';
}
$(function(){
var container = '#content_container';
$('nav')on.('click', 'a', function(){
var title = container_load(this);
$(container).prepend(title);
});
});

You could do the following :
var container = '#content_container',
title; // make title global
function container_load() {
var data = $(this).attr('data');
var dataObject = { command: data };
title = '<h2 data="' + dataObject.command + '">' +
dataObject.command + '</h2>';
};
$(function () {
$('nav') on.('click', 'a', function () {
container_load.call(this); // bind this to container_load
$(container).prepend(title);
});
});
But you could do even better :
$(function () {
$('nav') on.('click', 'a', function () {
var data = $(this).attr('data');
$('#content_container').prepend(
'<h2 data="' + data + '">' + data + '</h2>'
);
});
});

Related

Function within function in JavaScript - Need to understand this code:

I have below code within a function called render. How do I call the str variable value outside render function?
Also, please can you explain below code? I'm fairly new to js and head is hurting looking at the function calls having functions as a parameter.
My understanding is that app.getList is an object which takes function as a parameter? but it is not returning anything. Sorry, I'm lost here.
app.getList("FieldList", function(reply){
var str = "";
$.each(reply.qFieldList.qItems, function(index, value) {
str += value.qName + ' ';
});
console.log(str);
});
Full Code:
define(["jquery",
//mashup and extension interface
"qlik",
//add stylesheet
"text!./css/mystyle.css",
"client.utils/state",
"client.utils/routing"
],
function($, qlik, cssContent, clientState, clientRedirect) {
/*-----------------------------------------------------------------*/
// function redirect (sheetId){
// clientRedirect.goToSheet(sheetId, Object.keys(clientState.States)[clientState.state])
// }
/*-----------------------------------------------------------------*/
/*-----------------------------------------------------------------*/
var render = function($elem, layout) {
var html = '',
app = qlik.currApp();
//get list of tab objects and insert into div
app.getAppObjectList('sheet', function(arrayitem) {
//for each sheet in the app, create a list item
$.each(arrayitem.qAppObjectList.qItems, function(myindex, myvalue) {
//include the sheet id as the list item id to be used as a reference for active sheet
html += '<li id="' + myvalue.qInfo.qId + '">'; // onClick="redirect(' + value.qInfo.qId + ');
//wrap anchor tag to be used by bootstrap styling
html += '<a>';
//give the link the same name as the sheet
html += myvalue.qData.title;
html += '</a>';
html += '</li>';
});
html += '</ul></div>';
html += "<button id='myButton'> Click Me!! </button>";
console.log(arrayitem.qAppObjectList);
console.log(html);
//insert html into the extension object
return $elem.html(html);
});
/* Test Code Start from here */
app.getList("FieldList", function(reply) {
var str = "";
$.each(reply.qFieldList.qItems, function(key, value) {
str += value.qName + ' ';
});
console.log(str);
});
};
/*-----------------------------------------------------------------*/
return {
/*-----------------------------------------------------------------*/
paint: function($element, layout) {
console.count();
/*-----------------------------------------------------------------*/
$(function() {
$element.html("#myButton").click(function() {
// for(var mynum = 1; mynum <= 5; mynum++){
// alert('button test' + mynum);
// };
});
});
/*-----------------------------------------------------------------*/
render($element, layout);
/*-----------------------------------------------------------------*/
}
};
});
app.getList is probably asynchronous (meaning it runs in the background). The function you've passed to it is a callback. That function will be ran at some point in the future, once the AJAX call (or whatever asynchronous method is ran) is done.
Your callback is passed reply, which is the "return" value from getList(). You cannot access str from outside of this function. You need to do whatever code with reply and/or str in that function only.

Issue with JavaScript Array

Can you please take a look at following code and let me know why I am not able to run the program?
enter code here
$(document).ready(function()
{
var comp=new Array("AAPL","MSFT","XRTX&");
var t = setInterval(function(){getPrice();},200);});
function getPrice() {
for (var i=0;i<comp.length;i++){
$.getJSON('https://finance.google.com/finance/info?client=ig&q='+comp[i]+'&callback=?', function(response){
var stockInfo = response[0];
var stockString = '<div id="stockprice">';
stockString += 'Candente Copper: DNT $'+''+stockInfo.l+'';
stockString += '</div>';
$('#stockprice').replaceWith(stockString);
$("#stockprice:contains('-')").addClass('red');
$("#stockprice:contains('+')").addClass('green');
}
});
}​
Is there any problem with my Array object or other parts of program has issue? Please be advised that the code works fine without calling the array elements.
Thanks
Your {s, }s, (s and )s do not all match up correctly. Also, in order for your function to have a reference to the comp variable, they must both be in the same function scope, in this case: $(document).ready(function(){ ... });. You'll notice that I also increased your setInterval to 2000 (2s).
EXAMPLE
$(document).ready(function()
{
var comp = new Array("AAPL","MSFT","XRTX&");
var t = setInterval(function(){getPrice();},2000);
function getPrice()
{
for (var i=0;i<comp.length;i++){
$.getJSON('https://finance.google.com/finance/info?client=ig&q='+comp[i]+'&callback=?', function(response){
var stockInfo = response[0];
var stockString = '<div id="stockprice">';
stockString += 'Candente Copper: DNT $'+''+stockInfo.l+'';
stockString += '</div>';
$('#stockprice').replaceWith(stockString);
$("#stockprice:contains('-')").addClass('red');
$("#stockprice:contains('+')").addClass('green');
});
}
}
});​

How to pass a jquery function as a text, so it would be rendered in html and used by other script?

Hello there i got some code here;
<script type="text/javascript">
$(function(){
var playListURL = 'http://gdata.youtube.com/feeds/api/playlists/8BCDD04DE8F771B2?v=2&alt=json&callback=?';
var videoURL= 'http://www.youtube.com/watch?v=';
$.getJSON(playListURL, function(data) {
var list_data="";
$.each(data.feed.entry, function(i, item) {
var feedTitle = item.title.$t;
var feedURL = item.link[1].href;
var fragments = feedURL.split("/");
var videoID = fragments[fragments.length - 2];
var url = videoURL + videoID;
var thumb = "http://img.youtube.com/vi/"+ videoID +"/default.jpg";
HERE>>> list_data += '<button onclick="$('#bgndVideo').changeMovie('+ url +')">'+ feedTitle +'</button>';
});
$(list_data).appendTo(".playlist_elements");
});
});
</script>
This isnt working because of "$('#bgndVideo')" fragment that i need to pass as a text to be rendered in html so it looked like this in html:
<button onclick="$('#bgndVideo').changeMovie('http://www.youtube.com/watch?v=SOME_VIDEO_ID')"> Test </button>
How could i fix this so "$('#bgndVideo')" fragment would be treated as a text?
You would need to escape the 's:
list_data += '<button onclick="$(\'#bgndVideo\').changeMovie(\''+ url +'\')">'+ feedTitle +'</button>';
However, a cleaner approach might be something like this:
$list_data = $("<button>").html(feedTitle)
.click(function(){
$('#bgndVideo').changeMovie(url);
});

My view dont recieve data from my Controller

I will just show the part of the code I am having problens. If you think that you need to see all the code, let me know.
My Controller:
index: function() {
var documents = new App.Collections.Documents();
documents.fetch({
success: function() {
new App.Views.Index({ collection: documents });
},
error: function() {
new Error({ message: "Error loading documents." });
}
});
},
My View:
App.Views.Index = Backbone.View.extend({
initialize: function() {
console.log(this.documents);
this.documents = this.options.documents;
this.render();
},
render: function() {
if(this.documents.length > 0) {
var out = "<h3><a href='#new'>Create New</a></h3><ul>";
_(this.documents).each(function(item) {
out += "<li><a href='#documents/" + item.id + "'>" + item.escape('title') + "</a></li>";
});
out += "</ul>";
} else {
out = "<h3>No documents! <a href='#new'>Create one</a></h3>";
}
$(this.el).html(out);
$('#app').html(this.el);
}
});
The console.log of document code is: undefined
In the controller, var document is valid.
WHYYyY? How I can Access the json sent by the Controller in the view?
Thanks,
console.log(this.documents);
this.documents = this.options.documents;
Your using console.log before this.documents is even set.
UPDATE:
new App.Views.Index({ collection: documents });
this.documents = this.options.documents;
Wouldn't it be this.documents = this.options.collection; ? Because I don't see you passing the option.documents variable anywhere.
You pass collection: documents, so in your view you access it with this.collection.
Check out this jsfiddle that shows it working: http://jsfiddle.net/dira/TZZnA/
I dont know backbone too well ... but is this.documents defined before entering the initialize function ? seems not to be - try switching around the lines :
this.documents = this.options.documents; // define the variable
console.log(this.documents); // console log it

JavaScript jQuery binding

I am using jQuery to create an anchor and bind it with JavaScript function as follow:
$(document).ready
(
function()
{
var test = function(arg)
{
alert(arg);
}
var anotherTest = function(arg)
{
do something;
}
$('#id').click
(
var content = "Hello world";
var anchor = "<a href='javascript:void(0);' onclick='test(\"" + content + "\")' >test</a>";
$('#DivToBind').prepend(anchor);
);
}
);
And the problem is: the test function always alerts "a", no matter what the value of content is. If I change onclick function test to anotherTest, nothing happens but "anotherTest is not defined" appeared in the error console
Edit
To better identify my problem, I summarise my real code as follow
$(document).ready
(
function()
{
var deleteComment = function (comment)
{
commentInfo = comment.split('_');
var postid = commentInfo[0];
var enum = commentInfo[1];
var parentid = commentInfo[2];
var user = commentInfo[3];
var author = commentInfo[4];
var date = commentInfo[5];
$.get
(
"ajaxhandle.php",
{ref: 'commentdelete', pid: postid, d: date},
function(text)
{
if (text)
{
//alert(comment);
$('#' + comment).html('');
}
else
{
alert("Something goes wrong");
}
},
'text'
);
};
var test = function(arg) {alert(arg);};
$('#postCommentButton').click
(
function ($e)
{
$e.preventDefault();
var comment = $('#postdata').val();
var data = $('form#commentContent').serialize();
//alert(data);
$.post
(
"ajaxhandle.php",
data,
function($xml)
{
$xml = $($xml);
if ($xml)
{
//alert(45);
var success = $xml.find("success").text();
if (success == 1)
{
$('#postdata').val("");
var id = $xml.find("id").text();
var reference = $xml.find("reference").text();
var parentid = $xml.find("parentid").text();
var user = $xml.find("user").text();
var content = $xml.find("content").text();
var authorID = $xml.find("authorid").text();
var authorName = $xml.find("authorname").text();
var converteddate = $xml.find("converteddate").text();
var date = $xml.find("date").text();
var avatar = $xml.find("avatar").text();
comment = id + '\_wall\_' + parentid + '\_' + user + '\_' + authorID + '\_' + date;
//alert(comment);
var class = $('#wallComments').children().attr('class');
var html = "<div class='comment' id='" + comment + "' ><div class='postAvatar'><a href='profile.php?id=" + authorID + "'><img src='photos/60x60/" + avatar +"' /></a></div><div class='postBody' ><div class='postContent'><a href='profile.php?id=" + authorID + "'>" + authorName + " </a> <span>" + content + "</span><br /><div class='timeline'>Posted " + converteddate + "<br /><a href=''>Comment</a> | <a href=''>Like</a> | <a href='javascript:void(0);' onclick='deleteComment(\"" + comment + "\")' class='commentDelete' >Delete</a></div></div></div><div style='clear:both'></div><hr class='hrBlur' /></div>";
if (class == 'noComment')
{
//alert($('#wallComments').children().text());
//alert(comment);
$('#noComment').html('');
$('#wallComments').prepend(html);
}
else if(class = 'comment')
{
//alert(comment);
$('#wallComments').prepend(html);
}
}
else
{
alert("Something goes wrong");
}
}
else
alert("Something goes wrong");
},
'xml'
);
}
);
$(".comment").find('.commentDelete').click
(
function($e)
{
$e.preventDefault();
var comment = $(this).parent().parent().parent().parent().attr('id');
deleteComment(comment);
}
);
}
);
var test=... is inside a function, it's not going to be in scope on the page when you want to call it onclick the anchor.
to make it global you can leave off the var.
you could also do something like:
$(document).ready
(
function()
{
var test = function(arg)
{
alert(arg);
}
var anotherTest = function(arg)
{
//do something;
}
$('#id').click
(
function(){
var content = "Hello world";
var anchor = "<a href='javascript:void(0);'>test</a>";
$(anchor).click(function(){ test(content); });
$('#DivToBind').prepend(anchor);
});
}
);
Your example is incomplete. The call to bind click is missing a function wrapper (so it's a syntax error and won't even parse); there is no reference to calling anotherText;, and the anchor is never actually created, only a string. So it's not really possible to fix from there.
In general avoid creating dynamic content from HTML strings. As you are not HTML-escaping content, if it contains various special characters (<"'&) your script will fail and you may have a cross-site-scripting security hole. Instead, create the anchor and then write any dynamic attributes or event handlers from script:
$(document).ready(function() {
function test(arg) {
alert(arg);
}
$('#id').click(function() {
var content= 'Hello world';
$('test').click(function(event) {
test(content);
event.preventDefault();
}).appendTo('#somewhere');
});
});
It may be preferable to use a <button> styled like a link rather than a real link, since it doesn't go anywhere. A <span> styled as a link is another possibility, preferably with a tabindex attribute to make it keyboard-accessible in that case.
I think a lot of code is missing here.
But anyway, why won't you use jQuery power to bind events?
$(document).ready(function() {
var test = function(arg) {
alert(arg);
}
var anotherTest = function(arg) {
alert("another: " + arg);
}
$('#id').click(function() {
var content = "Hello world";
var anchor = $("<a href='#'>test</a>").click(function() { test(content); });
//apply anchor to DOM
});
});
I think this is what you're looking for:
$(document).ready(function() {
var test = function(arg) {
alert(arg);
};
var anotherTest = function(arg) {
alert("we did something else:" + arg);
};
$('#id').click(function() {
var content = "Hello world";
var anchor = $("<a>test</a>").click(function(event) {
event.stopPropagation();
// test(content);
anotherTest(content);
});
$('#DivToBind').prepend(anchor);
});
}
);
This example shows good use of event.stopPropagation(). Setting an anchor's href to void() or # is often a mistake.
If you're using jQuery, I would recommend using its event handler functions like so:
$(document).ready(function() {
var test = function(arg){
alert(arg);
}
var anotherTest = function(arg){
// do something;
}
$('#id').click( function(event){
var content = "Hello world";
var anchor = $("<a>test</a>");
anchor.click(function(event){
event.preventDefault(); // instead of javascript:void();
test(content);
});
$('#DivToBind').prepend(anchor);
});
});

Categories

Resources