I'm trying to use an object for javascript to hold my main elements etc. And my object will grab contents from the HTML elements. And I'm trying to use console.dir to see if my data is grabbed correctly.
The issue is, console.dir shows all values at once instead adding each element one by one. I'm using jQuery's each function.
Here is the fiddle ;
https://jsfiddle.net/365dzdhh/9/
Here is the code ;
(function(jQuery) {
'use strict';
window.DOER = {
saver:function(e){
e.preventDefault();
var sel = jQuery('.sel');
var data = {};
sel.find('.sell-me').each(function(){
//Shouldn't this show values one by one instead of all in one at once?
console.dir(data);
data = window.DOER.grabber(jQuery(this), data);
});
console.dir(data);
},
grabber:function(el,data){
data[jQuery(el).attr('id')] = jQuery(el).val();
return data;
},
init:function(){
jQuery(document).on('click', '.save-it', this.saver);
}
};
}($));
$(document).ready(function(){
window.DOER.init();
});
If you check the console, you'll see the log in the line "15" shows every details each time. Shouldn't it add each value by looping one by one? Am I missing something here?
I think this will give you the console info you want. console.dir(this) on line 15.
(function(jQuery) {
'use strict';
window.DOER = {
saver:function(e){
e.preventDefault();
var sel = jQuery('.sel');
var data = {};
sel.find('.sell-me').each(function(dataForEach){
//Shouldn't this show values one by one instead of all in one at once?
console.dir(this);
data = window.DOER.grabber(jQuery(this), data);
});
console.dir(data);
},
grabber:function(el,data){
data[jQuery(el).attr('id')] = jQuery(el).val();
return data;
},
init:function(){
jQuery(document).on('click', '.save-it', this.saver);
}
};
}($));
$(document).ready(function(){
window.DOER.init();
});
Related
What am I doing wrong, and how can one pass variables to a different function within the same wrapping variable/function.
Example:
function customFunctionWrap(){
this.myVar1 = 0;
this.getCurrentPosition = function(){
if (navigation.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){});
}
},
this.doSomething = function(){ // Works
//Do something, return
this.callWithParams(); //Works
},
//If I remove passing in 'value1',calling it elsewhere works
this.doSomethingWithParams = function(value1){
//Use value1
//Return
},
this.callWithParams = function(){
var value1 = 'xyz'; //Is a variable that changes based on some DOM element values and is a dynamic DOM element
this.doSomethingWithParams(value1); //THROWS TYPEDEF ERROR: this.doSomethingWithParams is not a function
this.getCurrentPosition();
}
};
var local = new customFunctionWrap();
local.doSomething(); //WORKS
I know there is another way to do it and then directly use customFunctionWrap.callWithParams(), but am trying to understand why the former approach is erroring out.
var customFunctionWrap = {
myVar1 : 0,
callWithParams : function(){
}
}
What JS sees:
var customFunctionWrap = (some function)()
returned function is fired, because the last (), so it has to yield/return something, otherwise, like in your code it is "returning" undefined.
So your given code does not work.
The very first fix is to delete last 2 characters from
var customFunctionWrap = (some function)()
to make it return constructor.
I have the following type of structure:
(function(){
var objects = [];
$('button.one').on('click', function(){
fetchObjects = function(objects) {
$.post("/fetchObjects")
.done(function(data){
objects = data;
console.log(objects.length);
});
}
fetchObjects(objects)
});
$('button.two').on('click', function(){
console.log(objects.length);
});
})();
You can see I have a variable objects that is local to this function. Initially its empty. When I click button.one I wish to populate objects with the returned value from some ajax request. It appears to work, however when clicking button.two, the objects variable is still an empty array.
Why isn't objects available in the jQuery callback?
I've also tried this approach but with the same results:
function callback(data) {
facilities = data
}
$.post("/fetchObjects")
.done(function(data){
callback(data);
});
What am I missing here? Please don't tell me to make "objects" global.
I don't know why you're passing objects as parameter. The following should work fine I think. Please let me know if you're trying to achieve something else.
(function(){
var objects = [];
$('button.one').on('click', function(){
fetchObjects = function() {
$.post("/fetchObjects")
.done(function(data){
objects = data;
console.log(objects.length);
});
}
fetchObjects()
});
$('button.two').on('click', function(){
console.log(objects.length);
});
})();
Let's simplify the code a bit. You have essentially this:
var objects = [];
fetchObjects = function(innerObjects) {
var data = ['a','b'];
innerObjects = data;
console.log(innerObjects.length);
};
fetchObjects(objects);
console.log(objects);
(I've changed the other objects variable's name just for clarity; the issue is the same even if it had the same name.)
When you call the function, innerObjects contains a reference to objects so modifying it would change the original array as well. But when you do
innerObjects = data;
now instead of modifying the array you're replacing the reference with something else. innerObjects "points" to data instead of objects and the original variable remains unchanged.
To make it work you'd need to loop through the data array (assuming it'll always be an array) and assign the contents to the objects reference one by one. This way you'll keep the original reference and modify the original array.
var objects = [];
fetchObjects = function(innerObjects) {
var data = ['a','b'];
for( var i = 0; i < data.length; i++ ) {
innerObjects[i] = data[i];
}
console.log(innerObjects.length);
};
fetchObjects(objects);
console.log(objects);
Or, in your actual code:
(function(){
var objects = [];
$('button.one').on('click', function(){
fetchObjects = function(objects) {
$.post("/fetchObjects")
.done(function(data){
for( var i = 0; i < data.length; i++ ) {
objects[i] = data[i];
}
console.log(objects.length);
});
}
fetchObjects(objects)
});
$('button.two').on('click', function(){
console.log(objects.length);
});
})();
I cant get that to work:
My json
[{"myicons":[{"icon":[{"rel":"1","id":"icon1","class":"bookmark desktop-icon ui-draggable","title":"bookmark1"}]},{"icon":[{"rel":"2","id":"icon2","class":"bookmark desktop-icon ui-draggable","title":"bookmark2"}]}]}]
My jquery each function finds the 2 icons but i cant seem to get the values... it keeps saying undefined.
var myicons = data[0].myicons;
$.each(myicons, function() {
var iconid = this.id;
alert(iconid);
});
Your JSON is full of array. i,e. data, myicons and even icon
$.each(data, function () {
var myicons = this.myicons;
$.each(myicons, function () {
var iconid = this.icon[0].id;
alert(iconid);
});
});
DEMO
I strongly suggest you to simplify yous JSON object
I am quite new to knockout.js, and I am enjoying learning how to make interfaces with it. But I have a bit of a wall while trying to make my interface more efficient. What I am trying to achieve is remove only the elements selected by $('.document_checkbox').serializeArray(), which contains the revision_id. I will then re-add the entries to the view model with a modified call to self.getDocument(), passing only the modified records which will be re-added. Can anyone help me how to remove the entries from the arrays based on the 'revision_id' values of $('.document_checkbox').serializeArray()
?
function Document(data) {
this.line_id = data.line_id
this.revision_id = ko.observable(data.revision_id);
this.status_id = ko.observable(data.status_id);
}
function DocumentViewModel() {
var self = this;
self.documents = ko.observableArray([]);
self.getDocument = function(){
//Reset arrays
self.documents.removeAll();
//Dynamically build section arrays
$.getJSON("/Documentation/Get-Section", function(allData) {
$.map(allData, function(item) {
var section = { name: item.array_name, display_name: item.display_name, documents: ko.observableArray([])};
self.documents.push(section);
})
//Add document objects to the arrays
$.getJSON("/Documentation/Get-Document", function(allData){
$.map(allData, function(item) {
var section = ko.utils.arrayFirst(self.documents(), function(documentSection) {
return documentSection.name === item.array_name;
});
section.documents.push(new Document(item));
});
});
});
}
self.updateStatusBatch = function(data,event){
$.post('/Documentation/Update-Status-Batch',
{
revision_id : $('.document_checkbox').serializeArray(),
status_id : event.currentTarget.value
}).done(
function(){
//This is where I get confused.
});
}
}
You should modify the /Documentation/Update-Status-Batch in order that it returns the deleted item id. So you will be able to remove it on the client side.
Try this "done" function:
function(removedItemId) {
self.documents.remove(function(doc){
return doc.status_id == removedItemId;
})
}
Take a look at the remove function.
I hope it helps.
When I run the code below, jQuery, repeatedly, puts a Window object in my array (and I'm sure the JSON doesn't include any references to the Window object). Is there any way to run this and keep the Window object out of my array?
Thanks
$.getJSON("../php/return_network_data.php",
function(fetch_data){
$.each(fetch_data, function(){
var index = this.id;
node_array[index] = paper.circle(this.xpos_init, this.ypos_init, 10).attr({"fill" : "#ff0000"})
$.each(node_array, function(){
console.log(this);
});
});
}
);
This should work..have to add index,value in each function
$.getJSON("../php/return_network_data.php",
function(fetch_data){
$.each(fetch_data, function(index,value){
var index2 = value.id;
node_array[index] = paper.circle(this.xpos_init, this.ypos_init, 10).attr({"fill" : "#ff0000"})
$.each(node_array, function(index,value){
console.log(value);
});
});
}
);
I'm not sure what paper.circle does exactly (is this raphael?), but I think it might be one of two things:
Removing the attr function from the paper command and adding it later.
node_array[index] = paper.circle(this.xpos_init, this.ypos_init, 10);
Adding key, value to the function in each:
$.getJSON("../php/return_network_data.php", function(fetch_data){
$.each(fetch_data, function(key, value){
var index = value.id;
node_array[index] = paper.circle(value.xpos_init, value.ypos_init, 10).attr({"fill" : "#ff0000"})
$.each(node_array, function(){
console.log(this);
});
});
});
Or possibly both?