What is the best way to get variables out of a get odata call. I have this code in a method where i want to work with the variable 'id', which i am getting with the odata call. I tried already callbacks but i cant get the right way. Do you have a solution for this? I tried also to put the call in an extra function, but then i get the problem that by return variable is undefined i a cant access it.
Update / additional:
I have a method where i am doing some odata updates and inserts. in my code below i am getting a id. this id i need in the next step for another odata update as parameter. My problem is that i cant work with the var id in the next steps of my code, because its only accessable in the oModel {} section.
oModel.read("/ZDEMA_LENDINGS2Set", {
urlParameters: {
"$select": "Id",
"$top": 1
},
success: function(oData, oResponse) {
console.log("Data", oData);
console.log("Response", oResponse);
var id = oData.results[0].Id;
},
error: function(oError) {
console.log("Error", oError);
}
}
Since this an UI5 app, I suggest using a local JSON Model and set the value as property.
this.getView().getModel('myLocalModel').setProperty("lendingId", oData.results[0].Id)
This has the advantage that you can use the two way databinding and or change listeners.
Alternative approach is to fire an event on the event bus.
Related
When trying this simple code:
function create_folder(name, parent_ID) {
var BM_folder = "";
chrome.bookmarks.create({title : name, parent_id : parent_ID }, function (new_folder) {
BM_folder = new_folder;
});
console.log("create folder in id : " + BM_folder.id);
return BM_folder.id;
}
I get undefined as output, but when I debug it works fine and I get the real bookmark ID. I have similar problems in more functions, I guess it's the same problem.
EDIT #1: fixed the vars, my real function has full strings, I simply can't post that way.
EDIT #2: thanks Marco Bonelli, is there a way to turn this into sync, so that I'll be able to use normal oop?
There are several problems in your code:
First of all, that function cannot work... you're using a hypen (-), and variable/function names cannot contain hypens in JavaScript, so change it in something else, maybe create_folder or createFolder. That's the same for your variable BM-folder, and parent-ID. Call them BMFolder and parentID.
Secondly, you are creating the object to pass to chrome.bookmarks.create() in the wrong way: parent-ID is both wrong and undefined. You should do: chrome.bookmarks.create({title: name, parentID: parentid}).
Inside your function, you're calling the chrome.bookmarks.create() method, which is asynchronous: this means that the code is processed separately from the body of your function, and when the method has finished working, it will call the callback function, which you provide as second argument. Basically when calling chrome.bookmarks.create() you have to wait until it's finished to continue, because if you try to access the BMfolder.id variable before the callback gets called it will obviously be undefined.
Now, to summarize what I said above, I'll show the right code for to achieve you're trying to:
function createFolder(name, parentid) {
chrome.bookmarks.create({title: name, parentID: parentid }, function (newFolder) {
console.log("Created the folder with ID: " + newFolder.id);
goOn(newFolder);
});
}
function goOn(BMFolder) {
console.log('Here is the folder: ', BMFolder);
// do something...
}
You cannot use return BMFolder.id, because your function is asynchronous, so the only thing you can do to know that the bookmark folder has been created is to call another function to continue. For example, you can name it goOn().
EDIT:
Is there a way to turn this into sync, so that I'll be able to use normal oop?
Unfortunately you cannot turn an asynchronous function into a synchronous one. Chrome extensions' methods are only asynchronous, therefore you have to work on that. By the way, working asynchronously is much more efficient than working synchronously, and you should get used to this programming style, because (as said before) Chrome extensions only work asynchronously, and so do many other JS frameworks and APIs.
I want to save the value of data and status in a variable and use it after the closing brackets of jquery GET/POST function.But alert comes only when it is inside .get braces.
$(document).ready(function(){
$.get("demo_test.asp",function(data,status){
v = data;
});
alert("Data:"+v);
});
As Jasper said, your alert is being triggered before the request is complete (async!). So, you have two options:
Do your logic inside the callback:
$.get("demo_test.asp",function(data,status){
v = data;
alert("Data:"+v);
//Process stuff here
});
Or pass the received data onto another function and work with it there
$.get("demo_test.asp",function(data,status){
v = data;
doStuff(v);
});
function doStuff(param) {
console.log(param);
}
You're absolutely correct; the code is working as it should... here's why:
The page loads and starts running code, it then hits the .get command and then keeps running, obviously making it to the 'alert' you have next. Since the .get function is still working on fetching the data before your page makes it to the 'alert' part... there's nothing to prompt.
You might want to string things together after the .get, using deferred objects. Look into: http://api.jquery.com/deferred.always/
This is a way of tacking on another function inside of the one fetching your data, so they depend on each other.
Simple answer, yes, you can store the data in a global variable and access it elsewhere. However, you must wait until it is ready.
The better way to do it is to instead store the jqXHR globally and simply add a done callback to it when you need to access the data.
var reqDemoTest = $.get(...);
//... some time later...
reqDemoTest.done(function(data){
console.log(data);
});
I am a newbie in backbone . I wanted to know when i do the following operation how i can get the model fetched values.
For example if i do something like following
this.model.fetch();
and i want to get a value for example
this.model.get("VALUE");
How i can make sure i get the right value which is fetched right now from the server. I am trying to do something like following but ofcourse this.model is not recognized inside the complete block.
this.model.fetch().complete(function(){
window.localStorage.setItem("VALUE", this.model.get("VALUE"));
});
I am stuck here. Does anybody have any ideas.
Well, I see two options: 1. just get rid of the complete block and use the functions separately.
this.model.fetch();
var value = this.model.get('value');
//or, if you want all of the values
// var values = this.model.toJSON();
// values.value -> the specific value
And I'm not very experienced with local storage, but why are you fetching a value and then setting it to local storage?
Or, 2. You could put your inner statements in a function, and bind it to the this:
initialize: function () {
_.bind('setItem', this);
},
setItem: function() {
// assuming this code works
window.localStorage.setItem("VALUE", this.model.get("VALUE"));
}
// elsewhere, and not familiar with complete, so I'm not certain how this works
this.model.fetch().complete(setItem);
I'd like to save an altered model to the database (set before). If the save succeeded redirect to another page (as example, could be any other action).
Model.save can have two optional properties. First is a hash of properties, and the second are options (like the success and error callback). http://backbonejs.org/#Model-save
somemodel.set({foo: 'bar'});
//lots of other logic and misc steps the user has to do
somemodel.save(); //on success should go here
Since the attributes are already set, I only need the callback.
In the past I did:
somemodel.save(somemodel.toJSON(), {
success: function() {
//other stuff
}
);
or passing the values again to the save method
somemodel.save(
{ foo: this.$('input').val()},
{ success: function(){}
);
I'm looking for a way to clean this up. The documents state, the model will fire a change state if there are new properties. But I'd want to redirect the user anyway (saving on new content or old/unaltered).
this does not exist:
somemodel.on('success', function(){});
and this, is only for validation:
if(somemodel.save()) { //action }
also "sync" is the wrong event (since it also works for destroy)
Any help?
somemodel.save(
{}, // or null
{
success: function(){}
}
);
will let you save a model with a specific callback without modifying existing keys.
And a Fiddle http://jsfiddle.net/h5ncaayu/
To avoid passing the success callback as an option, you can
use the promise returned by save :
somemodel.save().then(...youcallback...)
or use an event :
somemodel.on('sync', ...youcallback...);
somemodel.save();
Backbone.Model has a very convenient method called "changedAttributes" that will return a hash of changed attributes that you can pass to save. So...
model.save(
model.changedAttributes(),
{
success : _.bind(function() {...},this), //_.bind() will give scope to current "this"
error : _.bind(function() {...},this);
}
);
Nice and neat...
I am using Lawnchair to save data in js and retrieve it back for my mobile app.
I have this in my js file.
$(document).ready(function() {
//Lawchair set up
db = Lawnchair({name: 'db'},function(e){
console.log('storage open');
});
//store the 'username' key in storage
db.save({key:"username", value: "john"});
var name = ""
db.get("username", function(obj){
name = obj.value;
})
alert(name);
});
The problem is I always get "" in the name. I can never set any variable inside the callback function of "get" from Lawnchair object. Am I missing something?
Any help would be appreciated.
Thanks.
The database operation is asynchronous. Put your alert inside the callback to the ".get()" function.
As a general rule, any time you see a JavaScript API like this:
something(param, param, ... , function(result, result, ...) {
// ...
});
it's a good bet that the function may be an asynchronous mechanism, and that the callback function you supply will only be called later when an event actually transpires. In those cases you have to structure your own code such that activities you need to perform after the operation completes are done in code inside the callback.
(It's not always the case; some functional programming APIs for example take functions as arguments.)