Issues with getting object vars through a string - javascript

Not sure if the title makes sense but, I want to send data with an click event, this click event will get the data from a pre set var (in this case product101), as this var is formatted in JSON I cant seem to retrieve the data, it always returns a undefined. As the var is an object, but when I use the dataset var is an string right?
// inside a loop
<div class="container">
<script> var product<?=$id?> = {"category":"cars"}</script>
<div data-my-product="product<?=$id?>">
//all the product stuff
</div>
</div>
//located in the footer
$('[data-my-product]').click(function(){
//demo
var pro = $(this).data('my-product');
alert(pro.category);//returns undefined
})
When I click the product it returns a 'undefined' alert message.
Notice that the products are generated inside a loop.

Overview
Your best bet here is to create an object or Map with the things you want to look up this way, and then put them on it as properties or entries.
With an object:
var items = {
product101: {category: "cars"}
};
or if you want to be paranoid about the default inherited properties that exist on objects, you might use an object with no prototype:
var items = Object.create(null);
items.product101 = {category: "cars"};
then in your click handler:
alert(items[pro].category);
Live Example:
$('[data-my-product]').click(function() {
var pro = $(this).data('my-product');
alert(items[pro].category);
});
<div class="container">
<script>
var items = {
product101: {category: "cars"}
};
</script>
<div data-my-product="product101">
//all the product stuff
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
With a Map:
var items = new Map([
["product101", {category: "cars"}]
]);
then in your click handler:
alert(items.get(pro).category);
Live Example:
$('[data-my-product]').click(function() {
var pro = $(this).data('my-product');
alert(items.get(pro).category);
});
<div class="container">
<script>
var items = new Map([
["product101", {category: "cars"}]
]);
</script>
<div data-my-product="product101">
//all the product stuff
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Side note: Although you can access that data-* attribute's value (indirectly) using data, doing so sets up a data cache for the element and initializes that cache with the attribute's value. If you're just looking to get the string, .attr("data-my-product") is more direct. See this answer for more details.

Related

KoJs: bind a dynamic number of text boxes to elements of an array

I have a front-end which allows for adding and removing of text boxes suing the foreach binding. A text box looks something like this
<div id="dynamic-filters" data-bind="foreach: filterList">
<p>
<input type="text" data-bind="textInput: $parent.values[$index()], autoComplete: { options: $parent.options}, attr: { id : 'nameInput_' + $index() }"/>
</p>
</div>
What I want to do, as shown in the code above is to bind each of these dynamically generated text boxes to an element in the array using the $index() context provided by knockout.js
However it doesn't work for me, my self.values=ko.observableArray([]) doesn't change when the text boxes change.
My question is, if I want to have a way to bind these dynamically generated text boxes, is this the right way to do it? If it is how do I fix it? If it's not, what should I do instead?
Thanks guys!
EDIT 1
the values array is an observable so I thought I should unwrap it before use. I changed the code to
<input type="text" data-bind="textInput: $parent.values()[$index()], autoComplete: { options: $parent.options}, attr: { id : 'nameInput_' + $index() }"/>
This works in a limited way. When I add or change the content of text boxes, the array changes accordingly. However when I delete an element it fails in two ways:
If I delete the last item, the array simply doesn't change
If I delete an item in between, everything is shifted back
I suppose I have to add a function that changes the text-input value before destroying the text box itself.
Any help or advice on how to do this?
I would suggest taking the array of values and mapping it to some kind of model first, then dumping it into the filterList ko.observableArray. It can be as complex or as simple as need be.
That way you have direct access to those properties at the ko foreach: level instead of having to do the goofy index access.
I've added a simple knockout component example as well to show you what can be achieved.
var PageModel = function() {
var self = this;
var someArrayOfValues = [{label: 'label-1', value: 1},{label: 'label-2', value: 2},{label: 'label-3', value: 3},{label: 'label-4', value: 4}];
this.SimpleInputs = ko.observableArray(_.map(someArrayOfValues, function(data){
return new SimpleInputModel(data);
}));
this.AddSimpleInput = function(){
self.SimpleInputs.push(new SimpleInputModel({value:'new val', label:'new label'}));
};
this.RemoveSimpleInput = function(obj){
self.SimpleInputs.remove(obj);
}
}
var SimpleInputModel = function(r) {
this.Value = ko.observable(r.value);
this.Label = r.label;
};
var SimpleInputComponent = function(params){
this.Id = makeid();
this.Label = params.label;
this.Value = params.value;
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
}
ko.components.register('input-component', {
viewModel: SimpleInputComponent,
template: '<label data-bind="text: Label, attr: {for: Id}"></label><input type="text" data-bind="textInput: Value, attr: {id: Id}" />'
})
window.model = new PageModel();
ko.applyBindings(model);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!-- ko if: SimpleInputs -->
<h3>Simple Inputs</h3>
<!-- ko foreach: SimpleInputs -->
<input-component params="value: Value, label: Label"></input-component>
<button data-bind="click: $parent.RemoveSimpleInput">X</button>
<br>
<!-- /ko -->
<!-- /ko -->
<button data-bind="click: AddSimpleInput">Add Input</button>
EDIT (7/16/2020):
Mind explaining this without requiring lodash? I literally googled "how to lodash map using plain javascript". Excellent answer otherwise! – CarComp
In this scenario the lodash _.map method could be overkill unless you are executing the script in an environment that does not have native support for the vanilla array map method. If you have support for the vanilla method, go ahead and use that. The map method essentially iterates over each array using the method it is handed to return a transformed array of the original items. Implementation of vanilla code would look like so.
this.SimpleInputs = ko.observableArray(someArrayOfValues.map(function(data) {
return new SimpleInputModel(data);
}));
Here we are taking the values of someArrayOfValues and telling it to use each item to build a new SimpleInputModel and return it using that item data. [SimpleInputModel, SimpleInputModel, SimpleInputModel, SimpleInputModel] is what the new array turns into after mapping. Each of these items has all the functionality described in the SimpleInputModel class, Value and Label.
So with the new array you could, if you wanted, access the values like this as well self.SimpleInputs[0].Value() or self.SimpleInputs[0].Label
Hope that helps to clarify.

dojo dstore insert row

Can anyone assist me in inserting a row into a DGRID? The way I am doing it now is cloning a row, add it to the collection with the use of directives and then try to apply it to the grid. Below is the code I am using but the new row ends up getting added to the bottom instead of being inserted.
// Clone a row
theTable = tmxdijit.registry.byId(tableName);
firstRow = theTable.collection.data[theTable.collection.data.length-1];
firstRowDom = theTable.row(firstRow.id);
var cloneRow = json.stringify(firstRow);
cloneRow = json.parse(cloneRow);
// Get the row I want to add before
var theSelected = Object.keys(theTable.selection)[0];
if(theSelected.length > 0) {
var theRowID = theSelected[0];
}
theTable.collection.add(cloneRow, {beforeId: theRowID});
theTable.renderArray([cloneRow]);
There are two general ways to handle data insertion. One is to manually add data to an array, ensure it's properly sorted, and then tell the grid to render the array. A better way is to use an OnDemandGrid with a trackable store.
For dgrid/dstore to support simple dynamic insertion of rows, make sure the store is trackable, and that data items have some unique id property:
var StoreClass = Memory.createSubclass(Trackable);
var store = new StoreClass({ data: whatever });
var grid = new OnDemandGrid({
columns: { /* columns */ },
collection: store
});
By default dstore assumes the id property is "id", but you can specify something else:
var store = new StoreClass({ idProperty: "name", data: whatever });
If you want the data to be sorted, a simple solution is to set a sort on the grid (the grid will sort rows in ascending order using the given property name):
grid.set('sort', 'name');
To add or remove data, use the store methods put and remove.
var collection = grid.get('collection');
collection.put(/* a new data item */);
collection.remove(/* a data item id */);
The grid will be notified of the store update and will insert or remove the rows.
The dgrid Using Grids and Stores tutorial has more information and examples.
Instead of this, why don't you add the data directly to the grid store? See if this helps
https://dojotoolkit.org/reference-guide/1.10/dojox/grid/example_Adding_and_deleting_data.html
Adding and Deleting data
If you want to add (remove) data programmatically, you just have to add (remove) it from the underlying data store. Since DataGrid is “DataStoreAware”, changes made to the store will be reflected automatically in the DataGrid.
dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dijit.form.Button");
.
<div>
This example shows, how to add/remove rows
</div>
<table data-dojo-type="dojox.grid.DataGrid"
data-dojo-id="grid5"
data-dojo-props="store:store3,
query:{ name: '*' },
rowsPerPage:20,
clientSort:true,
rowSelector:'20px'
style="width: 400px; height: 200px;">
<thead>
<tr>
<th width="200px"
field="name">Country/Continent Name</th>
<th width="auto"
field="type"
cellType="dojox.grid.cells.Select"
options="country,city,continent"
editable="true">Type</th>
</tr>
</thead>
</table>
<div data-dojo-type="dijit.form.Button">
Add Row
<script type="dojo/method" data-dojo-event="onClick" data-dojo-args="evt">
// set the properties for the new item:
var myNewItem = {type: "country", name: "Fill this country name"};
// Insert the new item into the store:
// (we use store3 from the example above in this example)
store3.newItem(myNewItem);
</script>
</div>
<div data-dojo-type="dijit.form.Button">
Remove Selected Rows
<script type="dojo/method" data-dojo-event="onClick" data-dojo-args="evt">
// Get all selected items from the Grid:
var items = grid5.selection.getSelected();
if(items.length){
// Iterate through the list of selected items.
// The current item is available in the variable
// "selectedItem" within the following function:
dojo.forEach(items, function(selectedItem){
if(selectedItem !== null){
// Delete the item from the data store:
store3.deleteItem(selectedItem);
} // end if
}); // end forEach
} // end if
</script>
</div>
.
#import "{{ baseUrl }}dijit/themes/nihilo/nihilo.css";
#import "{{ baseUrl }}dojox/grid/resources/nihiloGrid.css";

Sorting out array of parent child relations where two children share a parent from an array and display it using div

I have the following data which gets served from a neo4j query, The data that gets sent back is in the format
home->parent->child1
home->parent->child2
home->parent2->child1
home->parent3->child1
home->parent3->child2
home->parent3->child3
I am trying to use javascript to display html which should be like this
<div id="parent1">
<div id="child1"></div>
<div id="child2"></div>
</div>
<div id="parent2">
<div id="child1"></div>
</div>
i tried loopong throigh the query and trying to get the parent to be the index of an object and the child to be values under it
i would do this like this in php
$jsonContents = (object)("parent"=>"child","parent"=>"child"....);
$array = array();
foreach($jsonContents as $jsCo=>$jsoCont){
$array[$jsoCont->parent][] = $jsoCont->child;
}
this would return the
$array as
home->parent1->[0]->child
->[1]->child
parent2->[0]->child...
This would let me avoid the check for uniqueness of the home parent category as well as put them in a hierarchy so i can interpret it properly in my View part of MVC, to create my div structure.
this is the url for the example json data
http://www.jsoneditoronline.org/?id=bdda268982eb431d361c25e9035bbc99
No answers to this, solved it by myself.
Here
var data = 'data shown in link above';
var myArr = [];
$.each(data, function(index, element) {
var parent = String(element.parent.properties.name);
var child = String(element.child.properties.name);
if(myArr[parent]){
myArr[parent][(myArr[parent].length)] = child;
} else {
myArr[parent] = Array(child);
}
});
Hope this helps people. :)

Add new values to attribute of the same object

I have a button that needs to add some values to an object attribute. The problem I have found is that I'm creating new objects on every click.
And what I need is to add new values to a specific attribute of a specific object.
I'm getting this
Object { id=0, title="Rolling Stones", sessionsBegin="1443564000000"}
Object { id=0, title="Rolling Stones", sessionsBegin="1443564000001"}
Object { id=0, title="Rolling Stones", sessionsBegin="1443564000002"}
What I need to generate is this
Object { id=0, title="Rolling Stones",sessionsBegin="1443564000000, 1443564000001,1443564000002"}
This on the controller part:
$scope.addItem = function(indexItem, title) {
$scope.cart = {
"id" : indexItem,
"title" : title
}
if ($scope.cart.id==indexItem){
$scope.cart.sessionsBegin=$scope.sessions[indexItem].date;
console.log($scope.cart);
}
}
This on the partial view side:
<div class="row" >
<div class="large-6 columns" >
<div class="panel">
<div ng-repeat="session in sessions">
{{event.id}} Date: {{session.date }} &nbsp
Availability: {{session.availability}} &nbsp
<a ng-click="addItem($index, session.title);" ng-show="addMore">ADD </a>
</div>
</div>
</div>
</div>
You need to concat a string to your current value, like that:
// Add a comma if needed:
$scope.cart.sessionsBegin += ($scope.cart.sessionsBegin) ? ', ' : '';
// and then add the value itself:
$scope.cart.sessionsBegin += $scope.sessions[indexItem].date;
Btw. usually you'd want a list of those sessionsBegin values to be an array - it will be much easier to work with. In that case I'd suggest:
if (!$scope.cart.sessionsBegin) {
$scope.cart.sessionsBegin = [];
}
$scope.cart.sessionsBegin.push($scope.sessions[indexItem].date);
Wouldn't changing $scope.cart.sessionsBegin=$scope.sessions[indexItem].date; to $scope.cart.sessionsBegin+=$scope.sessions[indexItem].date; do the trick?
In your code you redefine the cart object every time you press 'add' though. Hence why your console.log shows new objects every time.
$scope.cart = { ... } // this bit of code means you delete the 'old' $scope.cart and redefine it with new values
Does this work for you?
$scope.addItem = function(indexItem, title) {
$scope.cart = $scope.cart || {
"id" : indexItem,
"title" : title
}
if ($scope.cart.id==indexItem){
var sessionAsArray = $scope.cart.sessionsBegin.split(',');
sessionAsArray.push($scope.sessions[indexItem].date);
$scope.cart.sessionsBegin=sessionAsArray.join(',');
console.log($scope.cart);
}
}

Setting up AngularJS template with API javascript

I am new to AngularJS and want to convert my current website to AngularJS. Below is a section of my webpage that shows meetings pulled from Google calendar. I am using the API to do this. My questions is how would I convert the HTML/Javascript to an AngularJS template? Do I just use a controller and dump all the javascript in it?
Currently my HTML shows the first two results in my calendar list.
This is my HTML:
<section class="sub-box meetings-box">
<div class="meetings-section">
<span class="meeting-h1">NEXT MEETING</span>
<div class="next-meetings-section">
<div class="meeting-info meeting-time next-meeting-time-start"></div>
<div class="meeting-info meeting-time next-meeting-time-end"></div>
<div class="meeting-info next-meeting-title"></div>
<div class="meeting-info next-meeting-location"></div>
</div>
<span class="meeting-h2">UPCOMING MEETINGS</span>
<div class="upcoming-meetings-section">
<div class="meeting-info meeting-time second-meeting-time-start"></div>
<div class="meeting-info meeting-time second-meeting-time-end"></div>
<div class="meeting-info second-meeting-title"></div>
<div class="meeting-info second-meeting-location"></div>
</div>
</section>
This is part of my Javascript that shows the callback response API
request.then(function(callbackResponse) {
var entries = callbackResponse.result.items; //returns an array entries
//get meeting info
var nextMeeting = entries[0];
var nextMeetingTimeStart = nextMeeting.start;
var nextMeetingTimeEnd = nextMeeting.end;
var nextMeetingTitle = nextMeeting.summary;
var nextMeetingLocation = nextMeeting.location;
var secondMeeting = entries[1];
var secondMeetingTimeStart = secondMeeting.start;
var secondMeetingTimeEnd = secondMeeting.end;
var secondMeetingTitle = secondMeeting.summary;
var secondMeetingLocation = secondMeeting.location;
//formatting info
for (var x in nextMeetingTimeStart && nextMeetingTimeEnd &&
secondMeetingTimeStart && secondMeetingTimeEnd) {
var nextMeetingStart = nextMeetingTimeStart[x];
var nextMeetingEnd = nextMeetingTimeEnd[x];
var secondMeetingStart = secondMeetingTimeStart[x];
var secondMeetingEnd = secondMeetingTimeEnd[x];
var nextMeetingStartFormat = new Date(nextMeetingStart).toString('hh:mm tt');
var nextMeetingEndFormat = new Date(nextMeetingEnd).toString('hh:mm tt');
var secondMeetingStartFormat = new Date(secondMeetingStart).toString('hh:mm tt');
var secondMeetingEndFormat = new Date(secondMeetingEnd).toString('hh:mm tt');
$('.next-meetings-section').find('.next-meeting-time-start').text(nextMeetingStartFormat+'-');
$('.next-meetings-section').find('.next-meeting-time-end').text(nextMeetingEndFormat);
$('.upcoming-meetings-section').find('.second-meeting-time-start').text(secondMeetingStartFormat+'-');
$('.upcoming-meetings-section').find('.second-meeting-time-end').text(secondMeetingEndFormat);
}
$('.next-meetings-section').find('.next-meeting-title').text(nextMeetingTitle);
$('.next-meetings-section').find('.next-meeting-location').text(nextMeetingLocation);
$('.upcoming-meetings-section').find('.second-meeting-title').text(secondMeetingTitle);
$('.upcoming-meetings-section').find('.second-meeting-location').text(secondMeetingLocation);
With Angular you would want to use a directive for DOM Manipulation, a factory (there are other options but this is a good starting place) for http calls and to store data. The controller should be concerned with providing scope for the view.
Angular Documentation:
controllers
directives
providers - factories are included here.
You may want to spend a few hours going through a tutorial or two before refactoring into Angular. Code School has a good one for free.
Edit-
Looking at your code you would want to take care of the server response inside a factory - create properties on your factory for nextMeeting and secondMeeting, and have them set to your server response data each time you get a server response back with the data.
Inject your factory into a controller, then in your controller you can have properties your view will use like: nextMeetingStart, nextMeetingEnd, etc. The value of these properties can be functions that use the values on your factory's nextMeeting and secondMeeting properties to set their appropriate return values.
Then you can just reference those properties in your view. The values displayed in the view will update whenever the factory receives new data from the server.

Categories

Resources