FindMany overwritten doesn't work. Ember-data - javascript

In my project, if I ask my server for the records with id 1,2,3 like this (without spaces):
url?sites=id1 %2C id2 %2C id3
It will return a json file with the records for this ids.
So for this case I think I can have then cached if I manage to use findMany and make the RestAdapter make the call to the server in this way.
I have found the next, but it doesnt work, it continues calling:
GET topologymins/1,2
Adapter:
App.ApplicationAdapter = DS.RESTAdapter.extend({
findMany: function(store, type, ids) {
Ember.Logger.log("INSIDE THE findMany"); // NOT SHOWED
var url = type.url;
url = url.fmt(ids.join(','));
jQuery.getJSON(url, function(data) {
// data is an Array of Hashes in the same order as the original
// Array of IDs. If your server returns a root, simply do something
// like:
// store.loadMany(type, ids, data.people)
//store.loadMany(type, ids, data);
});
}
});
App.Topologymin.reopenClass({
url: '/something?ids=%#'
});
My call:
this.store.find('topologymin',[1, 2]);

Isn't this just because you're missing a return?
Oh... sorry your findMany isn't written correctly, I don't htink... it's missing a return... but that isn't actually what's wrong - it's not even calling the findMany because store.find() can't be passed an array of ids... you want this, I think: store.find('topologymin', { ids: [1,2] });
However, I think you'll have another problem in that findMany should have a return value in it... if you look at the default implementation, you'll see what I mean... it needs to return a promise, and you're not returning anything.

Related

How to pass an object as a parameter?

I am having troubles with some parts of my code randomly.
This object is declared in a angular controller.
this.tData = {
'questions':[],
'typeQuestion':[],
'category':[],
'dName':this.dName,
'tCodigo':this.tCodigo}
Then I got some data from others functions and push it into respective fields,
this.tData.questions.push(this.idQuestion) // this come from frontend ng-model
this.tData.typeQuestion.push(this.typeQuest) // this come from frontend ng-model
this.tData.category.push(this.idCategory)// this come from frontend ng-model
This construct my object fine. Doing console.log(this.tData) show me the object completely fine. But then when I pass it to the backend in this function of the angular service.
this.updateStuff = function(codStuff,tData){
return $http.put('/updateStuff' + codStuff,tData)}
The object that backend get doing console.log(params) is
{
questions:['exampleId'],
typeQuestion:['exampleData'],
category:[], // HERE IS THE PROBLEM
dName:'exampleName',
tCodigo:'exampleCod'}
Like you see category:[] is empty but doing console.log(tData) in the service of angular before I send it I see the correct data there.
I miss data when I send it to the backend. This problem happend to me in 3 others cases like this.
Why some arrays are ok in backend and why others are not?
I tried a lot of things but ever 1 item of the object I send to the backend go empty.
If you need more specific code tell me in comments.
Updates
Code here I push category in the controller:
this.getCategoryByName = function(){
this.bName = document.getElementById('seCategory').value;
Category.getCategoryByName(this.bName).then((result)=>{
this.idCategory = result.data.data._id; // this give me id of category
this.tData.category.push(this.idCategory);
})
}
2
This is where I call in frontend my functions:
<button class="btn btn-primary" ng-click="ctController.getCategoryByName(); ctController.updateTest();" > up </button>
This is the code of updateTest() function:
this.updateTest = function(){
Test.updateTest(this.codTest,this.tData).then(result=>{})
}
Above method call the angular service updateStuff
SOLVED
Solved adding a chain promise in the method getCategoryByName and adding the updateTest() method nested in getCategoryByName() method more or less like #T.J. Crowder sugest so I give it the response.
Code here I push category in the controller:
this.getCategoryByName = function(){
this.bName = document.getElementById('seCategory').value;
Category.getCategoryByName(this.bName).then((result)=>{
this.idCategory = result.data.data._id; // this give me id of category
this.tData.category.push(this.idCategory);
})
}
That tells us that you're calling updateStuff before Category.getCategoryByName has finished its work, and so before this.tData.category.push is called. The reason console.log seems to show you things in this.tData.category is (as I mentioned in a comment) because of deferred evaluation in the console.
This also explains why it happens sometimes: You have a race between that Category.getCategoryByName operation and the operation calling updateStuff. Sometimes, Category.getCategoryByName wins and so updateStuff includes the pushed information, other times the code calling updateStuff wins and so updateStuff doesn't have the information in this.tDate.category (yet).
this.getCategoryByName should return the promise chain:
this.getCategoryByName = function(){
this.bName = document.getElementById('seCategory').value;
return Category.getCategoryByName(this.bName).then((result)=>{
// ^^^^^^
this.idCategory = result.data.data._id; // this give me id of category
this.tData.category.push(this.idCategory);
});
};
...and then you should make whatever is calling updateStuff dependent on the resolution of that promise.
(You'll also want to ensure that something handles the chain's rejection path. Your current getCategoryByName ignores errors, which will lead to "Unhandled rejection" errors in the console if Category.getCategoryByName fails.)

How to reach JSON data inside parenthesis

I have a JSON response like this:
google.friendconnect.container["renderOpenSocialGadget"](
{
height: 200,
url: "http://username.github.io/",
"view-params": {"style":"light","url":"https://www.facebook.com/username","height":"258"},
"prefs": {"style":"light","url":"https://www.facebook.com/username","height":"258"}
}, skin);
I want to reach the values such as height, url, view-params but couldn't.
I tried this but it didn't worked:
console.log(google.friendconnect.container["renderOpenSocialGadget"].url);
The expression google.friendconnect.container["renderOpenSocialGadget"]( is equivalent to google.friendconnect.container.renderOpenSocialGadget(
Given that, we see that this is a method of an object, getting a JSON object and an additional parameter (skin) as parameters.
As the object is somehow "anonymous" parsed directly in to the function call, you can't access it anymore, once the function has consumed it.
Check, if google.friendconnect.container has getter methods (they usually have ...) by console.log(google.friendconnect.container).
EDIT
Just an Idea: you might catch the call and pass it over:
google.friendconnect.container["MyrenderOpenSocialGadget"] =
google.friendconnect.container["renderOpenSocialGadget"];
google.friendconnect.container["renderOpenSocialGadget"] = function(obj, skin) {
// do what you want with obj
console.log(obj.url);
//call original
google.friendconnect.container["MyrenderOpenSocialGadget"](obj, skin);
});

Client side mongodb-like queries in backbone

Is there a way to check whether an object is matched by a mongodb-type query on the client side? For instance:
function is_matched(obj,query){
...something magic here...
}
var potato = {val:1}
is_matched(potato,{val:1})
returns true, and
is_matched(potato,{foo:bar})
returns false.
The tricky part is that I'd like for it to take the same kinds of queries as mongodb so that you can do more complicated things like regular expressions and the like. Is there something on the client side that will emulate mongo's query matching behavior?
I would suggest using Loki.js http://lokijs.org/#/ it is an in-memory no-sql database with a mongodb like query syntax (it works on browser as well)
and here's how your current example can be mimicked using loki.js :
db = new loki('loki.json')
children = db.addCollection('children')
children.add({val: 1})
children.find({val: 1}) // returns [{val: 1}]
children.find({foo: "bar"}) // returns [] (empty collection)

Passing a currying function from Rails to JavaScript

I need to pass an URL to a .js file. This URL is generated by Rails and accepts one argument.
#routes
get "my_super/:some_id" => "controller1#my_super",
#index.html.haml
:javascript
var myUrlFunc = "#{my_super_url}"; //my_super_url(...) expects one argument
And a .js file:
$.ajax({
url: myUrlFunc($("#active_user_id"));
})
//................
The point is I don't know some_id initially as it's dynamically chosen, it's chosen from a drop down list. So I have to a function myUrlFunc which takes one argument and returns the URL instead of the URL itself. I thought this would work that it didn't due to an error:
No route matches {:action=>"my_super", :controller=>"controller1"} missing required keys: [:some_id]
What do I do about this?
As you have found out, the routing helper won't let you call it with missing parameters. Further more ruby doesn't know how to serialize a ruby method into a javascript function.
One simple, if not particularly elegant would be to pass a dummy value to my_super_url. Your function would then be along the lines of
var myUrlFunc = function(id){
var base = #{my_super_url("--DUMMY--")};
return base.replace("--DUMMY--", id);
}

Jquery $.get() manipulating data resulting from query in javascript

I have a $.get() statement, which returns this (result from a console.log()):
{"desc":"asdasda","dateD":"2012-08-31","dateE":"2012-09- 01","image":"fasdasdasd","categorie":"3"}
Now when I try, in Javascript, to manipulate the array, everything holds an undefined or null value:
var image = data.image;
desc = data.desc;
dateD = data.dateD;
dateF = data.dateE;
image = data.image;
categorie = data.categorie;
Note: the DateF= data.dateE is not a mistake.
Note2: Those statements are all held within the function (data){} function contained in the $.get().
All those assignments return undefined. What am I doing wrong? I have read and re-read the official jQuery doc, without success.
Make sure you set the dataType of the return to json.
If you don't do this, the result data may be a string and you will need to use JSON.parse(data) to turn it into a usable object.
For example:
$.get(url, getData, function(data){
//your fn...
}, 'json');

Categories