How to get a random value from a Fixture Data in Ember - javascript

I'm playing with a sample Ember app that shows all the data stored in a Fixture, and finally tries to show a random data from the fixture.
Complete Demo here: http://jsbin.com/ifatot/2/edit
Everything works fine, however, I'm not able to get a random index out of the Ember Data. I'm trying to find its length and grab the random index but I believe the length is always coming up as 0, even though I have data in there.
The function looks like this:
App.ThoughtsController = Ember.ArrayController.extend({
randomMessage: function() {
var thoughts = this.get('model');
var len = thoughts.get('length');
var randomThought = (Math.floor(Math.random()*len));
return thoughts.objectAt(randomThought);
}.property('model')
});

You should add the length property as another dependent on the randomMessage computed property. This will allow the content to have finished resolving and have a length.
randomMessage: function() {
var len = this.get('length');
var randomThought = (Math.floor(Math.random()*len));
return this.objectAt(randomThought);
}.property('model', 'length')
Here's an updated jsbin.

Related

Firebase - For item in directory

I have some data in a directory and I want to retrieve the value of a certain object e.g. Get the value of "NVR".
Another task I need to do is have a 'for' loop to go over and get information about different questions from the following data. I would need to get the number e.g. "001" and the items inside of that subdirectory. And it would also need to go through every directory in 'questions' such as NVR or MTH.
For the first one, you can try this:
firebase.database().ref().child("unique").on('value', function(snapshot) {
var datas = snapshot.val();
var nvr=datas.NVR;
)};
For the second one try this:
firebase.database().ref().child("questions").child("NVR").on('value', function(snapshot) {
snapshot.forEach(function(child) {
var keys=child.key;
var datas = child.val();
var correcta=child.val().correctAnswer;
var num=child.val().numberOfAnswers;
//etc
});
});
the first one the snapshot will be at unique, then you will be able to retrieve the child NVR.
In the second one, you iterate inside NVR and retrieve the key using var keys=child.key;
Try something like this for going through every directory in questions and for each one getting all the questions in it :
firebase.database.ref('questions').on('value').then((snapshots) => {
//print whole questions group (nvr, mth, etc)
console.log(snapshots.val())
snapshots.forEach((snapshot) => {
//print each question in question group
console.log(snapshot.val())
})
}
Both Peter's and Egor's answers load all data under unique. Since you know the key of the item whose value you want to retrieve, you can load this more efficiently with:
firebase.database().ref("unique/NVR").on('value', function(snapshot) {
var nvr=snapshot.val();
)};

localStorage, i cant seem to call the data

var dataArray = [];
localStorage.itemListRecord = JSON.stringify(dataArray);
dataArray = JSON.parse(localStorage.itemListRecord);
var dataObj = {
listItem: textInput,
};
dataArray.push(dataObj);
I am trying to save the data on my todo list, I get the items pushed into an object, that i "stringify" and "parse"...
But I am not quite sure how I then call the saved data..
And it seems like the items ain't getting to the localStorage at all..
https://jsfiddle.net/headbangz/kn0bw6yw/
This example should work.
var textInput = "example";
var dataObj = {
listItem: textInput,
};
var dataArray = [];
dataArray.push(dataObj);
localStorage.setItem("itemListRecord", JSON.stringify(dataArray));
dataArray = JSON.parse(localStorage.getItem("itemListRecord"));
dataArray.push(dataObj);
localStorage.setItem("itemListRecord", JSON.stringify(dataArray));
I notice that when the script starts you are immediately clearing the localStorage.itemListRecord location that you are using, before you try to read from it. So, it will always be empty upon initialization and this script will never be able to use what is there:
// Data Object
var dataArray = [];
// CHANGED: I commented out the line below so that the localstorage is not cleared
// localStorage.itemListRecord = JSON.stringify(dataArray);
dataArray = JSON.parse(localStorage.itemListRecord);
// CHANGED: added these lines only for debugging
console.log('existing data');
console.log(dataArray);
Also, I notice that there is not any code yet that will add to the local storage, when a new todo list item is added:
function listTodoItem(textInput) {
var dataObj = {
listItem: textInput,
};
dataArray.push(dataObj);
// CHANGED: added this line to update localstorage whenever an items is added to the list
localStorage.itemListRecord = JSON.stringify(dataArray);
// CHANGED: added these lines only for debugging
console.log(dataArray);
console.log(dataObj);
Note that, even with these changes, the list still doesn't reflect what is in local storage, because it doesn't build the initial unordered list from what is in the dataArray. More code needs to be added for that too.
But with what I've suggested here, and looking at the output in the console log when you re-run the jsfiddle, you should be able to see that the localstorage part is working, and you can get past this bit.
I haven't seen that API
I use what is listed on Mozilla's site https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Appears to be get and set okay in this example tied to your click handler
Check the console for logs
Per commentary below - exact click handler changed
// Add value from the input field
document.getElementById("new-btn").addEventListener('click', function() {
var itemValue = document.getElementById("my-input").value;
if (itemValue) {
listTodoItem(itemValue);
localStorage.setItem('data', JSON.stringify(itemValue));
console.log(localStorage.getItem('data'));
}
});

How to store data in an array that is stored in a variable?

Following is my problem:
I am testing a system now, that has multiple ID's in every request. There are 2 ID's I want to store in an array and let them run again a response later.
Following is the Body I recieve
{
"id" = 1234;
"Name" = "Meier"
}
So, I store the ID normally with
var body = JSON.parse(responseBody);
postman.setEnvironmentVariable("ID", body.id);
with that I can store 1 ID in the variable, but can't put a second one in it. For that I would have to duplicate the request, set a second variable, change code everytime the needed cases are changed.
What I want to know now is: How can I store multiple ID's in a Environment Variable to compare them with a response at the end of the collection?
I'm not entirely familiar with postman, but if I'm understanding correctly and you want to store up the Id's from the response then you could use something like -
var body = JSON.parse(responseBody);
var storedIds = postman.getEnvironmentVariable("ID");
if(storedIds) {
storedIds.push(body.id)
} else {
storedIds = [body.id]
}
postman.setEnvironmentVariable("ID", storedIds);
Edit
From my own googling, it appears you cannot store arrays in environment variables in postman. Therefore you could try doing something like this -
var body = JSON.parse(responseBody);
var storedIds = postman.getEnvironmentVariable("ID");
if (storedIds) {
storedIds = storedIds.concat(',' + body.id)
} else {
storedIds = body.id
}
postman.setEnvironmentVariable("ID", storedIds);
Then when you want to read it back out to loop over it or whatever you want to do you can use
var idsArray = postman.getEnvironmentVariable("ID").split(',')
which will split the string up to give you an array.

Parsing a JSON object with Javascript, just won't work

I'm using this code to get a JSON file stored in the same folder.
var schedtotal = 0;
var requestURL11 = 'schedtotal.json';
var request11 = new XMLHttpRequest();
request11.open('GET', requestURL11);
request11.responseType = 'json';
request11.send();
request11.onload = function() {
window.superHeroes11 = request11.response;
populateHeader11(superHeroes11);
}
function populateHeader11(jsonObj) {
window.schedtotal = jsonObj.total;
console.log("populateHeader function has activated");
console.log(jsonObj);
}
The file looks like this:
{"total": 3}
It's valid JSON. I'm trying to extract the value of total using the same exact method that I've used successfully for all the other JSON parsings in the rest of the file (which I have not included here).
When populateHeader11 is called, it doesn't change schedtotal to equal total. It remains at its original setting of 0. The console log returns from the function as having activated and also returns the JSON file so I know it can access it at least.
I've tried changing .jsonObj.total to .jsonObj['total'] and it didn't change anything.
Previous times I've screwed around with this, it has sometimes returned an error saying it can't get 'total' from null. Now it just doesn't return anything in its current state. What is going on?
You need to parse the JSON string into an object before you try and access the total field.
var jsonString = "{\"total\": 3}";
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.total);

Backbone collection fetch imported incorrectly

I have a collection which is fetched from a REST endpoint, where it receives a JSON.
So to be completely clear:
var Products = Backbone.Collection.extend({
model: Product,
url : 'restendpoint',
customFilter: function(f){
var results = this.where(f);
return new TestCollection(results);
}
});
var products = new Products();
products.fetch();
If I log this, then I have the data. However, the length of the object (initial) is 0, but it has 6 models. I think this difference has something to do with what is wrong, without me knowing what is actually wrong.
Now, if I try to filter this:
products.customFilter({title: "MyTitle"});
That returns 0, even though I know there is one of that specific title.
Now the funky part. If I take the ENTIRE JSON and copy it, as in literally copy/paste it into the code like this:
var TestCollection = Backbone.Collection.extend({
customFilter: function(f){
var results = this.where(f);
return new TestCollection(results);
}
});
var testCollectionInstance = new TestCollection(COPY PASTED HUGE JSON DATA);
testCollectionInstance.customFilter({title: "MyTitle"});
Now that returns the 1 model which I was expecting. The difference when I log the two collections can be seen below. Is there some funky behaviour in the .fetch() I am unaware of?
Edit 2: It may also be of value that using the .fetch() I have no problems actually using the models in a view. It's only the filtering part which is funky.
Edit 3: Added the view. It may very well be that I just don't get the flow yet. Basically I had it all working when I only had to fetch() the data and send it to the view, however, the fetch was hardcoded into the render function, so this.fetch({success: send to template}); This may be wrong.
What I want to do is be able to filter the collection and send ANY collection to the render method and then render the template with that collection.
var ProductList = Backbone.View.extend({
el: '#page',
render: function(){
var that = this; /* save the reference to this for use in anonymous functions */
var template = _.template($('#product-list-template').html());
that.$el.html(template({ products: products.models }));
//before the fetch() call was here and then I rendered the template, however, I needed to get it out so I can update my collection and re-render with a new one (so it's not hard-coded to fetch so to speak)
},
events: {
'keyup #search' : 'search'
},
search : function (ev){
var letters = $("#search").val();
}
});
Edit: New image added to clearify the problem
It's a bit tricky, you need to understand how the console works.
Logging objects or arrays is not like logging primitive values like strings or numbers.
When you log an object to the console, you are logging the reference to that object in memory.
In the first log that object has no models but once the models are fetched the object gets updated (not what you have previously logged!) and now that same object has 6 models. It's the same object but the console prints the current value/properties.
To answer your question, IO is asynchronous. You need to wait for that objects to be fetched from the server. That's what events are for. fetch triggers a sync event. Model emits the sync when the fetch is completed.
So:
var Products = Backbone.Collection.extend({
model: Product,
url : 'restendpoint',
customFilter: function(f){
var results = this.where(f);
return new TestCollection(results);
}
});
var products = new Products();
products.fetch();
console.log(products.length); // 0
products.on('sync',function(){
console.log(products.length); // 6 or whatever
products.customFilter({title: 'MyTitle'});
})
It seems like a response to your ajax request hasn't been received yet by the time you run customFilter. You should be able to use the following to ensure that the request has finished.
var that = this;
this.fetch({
success: function () {
newCollection = that.customFilter({ title: 'foo' });
}
});

Categories

Resources