Get row data from dojo store - javascript

I have this javascript of code
var store;
function dataBind(servletPath){
store = Observable(Cache(JsonRest({target:servletPath}), Memory()));
}
The servletPath will return me a json string that looks like this.
[{"colNo":1,"colMemberId":108}]
Lets say I call this javascript function and it returns a record to me. How do I get the "colMemberId" from the store?

If your function returns a Dojo store object then you can access it's contents through the use of it's query() function like so
var store;
function dataBind(servletPath){
return store = Observable(Cache(Memory({data:[{"colNo":1,"colMemberId":108}]}), Memory()));
}
console.log("store: ", dataBind().query({}));
Calling the query function with an empty object as a parameter will return an array containing the entire contents of the store.
Documentation: http://dojotoolkit.org/reference-guide/1.10/dojo/store/Memory.html
Here is a jsFiddle example : http://jsfiddle.net/kagant15/y7ec4byk/4/

Related

pass object angular js $state.go

I need to pass my object using $state.go method. my list date is
$scope.oldList = $stateParams.userDetailList;
when console above
console.log($scope.oldList)
data showed correctly. therefor no issue about the data.
now when I call go back function, I need to pass $scope.oldList data to the other page.
my goback function is as below. this function is in (sanction-screening-view page)
$scope.goBack = function () {
$state.go("app.sanction-screening");
};
I need to pass my $scope.oldList object to the "app.sanction-screening" route. how i do it.
The go function can take two parameters:
$state.go('app.sanction-screening', $scope.oldList);

How do I update localStorage items?

I'm having a problem where the cached object doesn't resemble the correct data so I figured it I can push up the most uptodate version to the browser cache it will solve my problem.
How do you update your localStorage with a new object? So if I had a controller with that had an assessment updated. How can I push that assessment object up to the localStorage?
To do that with native JavaScript, you would do something like this:
localStorage.setItem('itemKey', JSON.stringify(yourObject));
var item = JSON.parse(localStorage.getItem('itemKey'));
Within the context of angular, you should make a localStorage service as a wrapper around localStorage and inject it into your service or controller. Or you could inject $window and use it directly off of that like: $window.localStorage
A response specifically for the asker of this duplicate question:
LocalStorage can only store strings, which is why you're stringifying your object before storing it. To manipulate the stored string as an object, you can pass it to JSON.parse (assuming it's properly JSON-formatted). Then to store the modified version, you need to convert it back into a string.
// Creates JSON-formatted object, converts it to a string and stores the string as "ship"
const ship = { name: "black pearl", captain: "Jack Sparrow" };
const originalStringifiedForStorgage = JSON.stringify(ship);
localStorage.setItem("ship", JSON.stringify(ship));
// Retrieves the string and converts it to a JavaScript object
const retrievedString = localStorage.getItem("ship");
const parsedObject = JSON.parse(retrievedString);
// Modifies the object, converts it to a string and replaces the existing `ship` in LocalStorage
parsedObject.name = "newName";
const modifiedndstrigifiedForStorage = JSON.stringify(parsedObject);
localStorage.setItem("ship", strigifiedForStorage);
If the object is in JSON format (not sure if Angular uses a different format) you could probably use the setItem() and getItem() methods to update and retrieve local storage items!
For example taken from the following post:
http://thejackalofjavascript.com/storing-objects-html5-local-storage/
var me = {name:'myname',age:99,gender:'myGender'};
localStorage.setItem("user",me);
//fetch object
console.log(localStorage.getItem("user")); // will return "[object Object]"
You can use full featured Angular module angular-local-storage
An AngularJS module that gives you access to the browsers local
storage with cookie fallback
set
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
function submit(key, val) {
return localStorageService.set(key, val);
}
//...
});
get
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
function getItem(key) {
return localStorageService.get(key);
}
//...
});
setItem wont work instead it will create another item in localStorage with the same name
Instead directly use
localStorage.item = (what ever the change that you want in the item)

Bakbone model extend filtering a json

I am very new in backbone js.
I am trying to filter some specific key and values in backbone js model extend here is the code below.
var items = ["open","close"];
var ReportModel = Backbone.Model.extend({
url: function() {
return tab+".json";
}
});
where tabe is dynamic json file name.In my json file many key value pair are there but I want to load only those key which is mentioned in items list.
I saw some where using parse function but that a;so did not work out.Please do let me know how to filter the specific keys form json using the backbone.
I also tried creating a dict from json and pass it to model like.
var ReportModel = Backbone.Model.extend({
"open":{.......}
});
but there I am getting issue.
throw new Error('A "url" property or function must be specified');
Please help me out with this.
You are missing some steps to be succesfull on your task.
First a note about the error: Backbone expects a string on the url property while you're passing a function. If you want to use a function to return your url dinamically use urlRoot.
Now onto the real coding:
since you talk about a json file that has multiple key value, maybe you should declare your model as a key-value object, and then create a Backbone.Collection that will wrap your models.
A Backbone.Collection expose a lot of utilities that can help us modeling the results, in this case by using the where() function of our collection you will be able to filter the data after you have retrieved from the remote file.
Alternatively to filter your collection if you need more control over the function you can always call the undescore function filter() .
Please refer to the official documentation of underscore and backbone, as you will find a lot of functions that can help you and most of them have an example that shows how to use them.
Now that we have everything lets create our Backbone.Collection that will wrap your already defined model:
var ReportCollection = Backbone.Collection.extend({
model: ReportModel,
urlRoot: function(){
return 'yoururl.json';
}
});
now if you want to filter the result you can simply fetch the collection and perform a filter on it:
var myReports = new ReportCollection();
//call the fetch method to retrieve the information from remote
myReports.fetch({success: function(){
//the collection has been fetched correctly, call the native where function with the key to be used as a filter.
var filteredElements = myReports.where({my_filter_key : my_filter_value});
});
in your filteredElements you will have an array of object made up of all the model that matched the key/value passed to the where function.
If you need a new Collection from that you just need to pass the result as argument: var filteredCollection = new ReportCollection(filteredElements);
You can use _.pick() in the parse method as shown below:
var items = ["open", "close"];
var ReportModel = Backbone.Model.extend({
url: function() {
return tab + ".json";
},
parse: function(response) {
return _.pick(response, items);
}
});

Firebase - Object vs Array and Returning a .key()

I'm using firebase + angularfire for a project that involves multiple users editing data at the same time (which would make an object ideal) as well as the need to quickly sort and filter the data on the fly (ideal for an array).
So, would it be better for me to:
1) use FirebaseObject and then use an angular toArray filter for sorting
2) use FirebaseArray and just make sure to use $add to ensure use of unique IDs (even storing the push ID as a property of the pushed object itself).
Currently, we are using the second option, which leads me to my second question:
When I use $push, how can I return the ref.key() back to the controller?
Modifying the example from the API guide:
var list = $firebaseArray(ref);
var addItem = function(itemDataObject) {
list.$add(itemDataObject).then(function(ref) {
var id = ref.key();
console.log("added record with id " + id);
list.$indexFor(id); // returns location in the array
});
};
How can I get that id variable to be returned when the addItem function is called? Even if I declare a variable outside the list.$add function and set the variable within the function, I get an undefined result.
One way would be to fall back to using Firebase's regular JavaScript SDK.
var list = $firebaseArray(ref);
var addItem = function(itemDataObject) {
var newItemRef = ref.push(itemDataObject);
var id = newItemRef.key();
console.log("added (or still adding) record with id " + id);
return id;
};
But if you need the key() of the new ref for anything more than displaying it, you'll need to wait until it's available.
In that case, the easiest approach is to return the promise:
var list = $firebaseArray(ref);
var addItem = function(itemDataObject) {
return list.$add(itemDataObject);
};
What happens next, depends on the calling code and what you want it to do.
Since you want to return the result of an asynchronous operation, you may benefit from reading my answer here and the links in it: Asynchronous access to an array in Firebase
One possible issue seems like having variable declaration of id even though that variable is declared globally.
For example:
var id;
function setIDVal1(){
var id=10;
}
function setIDVal2(){
id=101;
}
function getIDVal(){
alert(id);
}
Check this fiddle for the local variable issue & check this fiddle for an example to get the ID.

Best way of getting the key after $add

I am using angularFire v 0.5.0
On my returned object I do a $add.
What would be the best way to get the generated key?
It must be something in the succes callback of the $add, because the key will come back asynchrounlusly?
scope.settings = $firebase(ref);
scope.settings.value = {
vat: {
inclusive: true
}
}
}
scope.settings.$add (scope.settings.value).then( function ( {
scope.settings.key = ???
});
note: this is not the actual code, this is just to clarify the problem.
The actiual code is inside a factory in the loaded event, and there is a check if there is already a settings object inside the database.
This somewhat strange construct is to make it easyer for consumers of the factory to change the settings. The settings is a singleton. AngularFire does not return a array of objects, but every item is a object in the settings, with its own key.
$add returns a Firebase ref. Call name() on that ref.
scope.settings.$add(…).name();
See https://github.com/firebase/angularFire/blob/master/angularfire.js#L127.
from the angularfire docs:
The $add method takes a single argument of any type. It will append this value as a member of a list (ordered in chronological order). This is the equivalent of calling push(value) on a Firebase reference.
from the firebase docs (about push()):
Returns
A Firebase reference for the generated location.
so, i think the "key" that you want is the return value of the $add.
Maybe they've changed it in newer versions, now it works like this:
$add() will return a promise. You have to use the callback which runs on success. For example:
var something = $scope.somethings.$add({name: "foo"});
something.then(function(e) {
console.log(e.name())
});
This allows you to perform different actions based on the outcome of the save/write attempt to Firebase.

Categories