When should I use dojo.data.ItemFileWriteStore's _saveEverything function? - javascript

I am using dojo 1.6 version. My understanding is: if store._saveEverything = saveCompleteCallback; is defined, then the callback function saveCompleteCallback will be called only when store.save() is called?
And do I need to use the 1st and 2nd params defined in the callback function saveCompleteCallback(saveSuccess, saveFail, storeData){}? Cause I only know that I need to use them when calling store.save({onComplete: saveSuccess, onError: saveFail})?

First I only use _saveEverything when I need a dojox.data.dataGrid's data to be xhrPosted and then xhrGeted.
Assume you define: store._saveEverything = saveCompleteCallback;
I just figured out, that including the 1st and 2nd params of saveCompleteCallback(saveSuccess, saveFail, storeData) are necessary, because an extra saveSuccess() and saveFail() function needs to be called again in saveCompleteCallback(). e.g.
// When you wanna upload datagrid, you click upload button
Store.save({ onComplete : saveSuccess, onError : saveFail });
// Definition of saveCompleteCallback
function saveCompleteCallback(saveSuccess, saveFail, storeData) {
dojo.xhrpost(
url: posturl,
postData:storeData,
load: function(data) {
// saveSuccess() must be invoked here again,
// otherwise this function will not be called
saveSuccess();
}
);
}
function saveSuccess() {
dataGrid = dijit.byId('YOUR DATAGRID ID');
dojo.xhrGet(
url: geturl,
load: function(date){
// The reason that a new xhrGet is called is db data is updated
// So the dataGrid will have no value after xhrPost
var store = new dojo.data.ItemFileWriteStore({data: data});
store._saveEverything = saveEverything;
store.clearOnClose = true;
store.urlPreventCache = true;
dataGrid.setStore(store);
}
);
}

Related

Call javascript function from another js file

I have a javascript file that reads the input from textbox inputs in MVC/AngularJS. The method looks like the following:
$scope.Clients_CW = {
....
}
function sendForm(data)
{
$scope.Clients_CW = data;
var submitData = registrationService.SaveFormData($scope.Clients_CW);}
I'm using the jQuery wizard with next, previous and finish buttons. This is in a different javascript file to the code above. My finish button looks like the following:
$($this.buttons.finish).click(function() {
if(!$(this).hasClass('buttonDisabled')){
if ($.isFunction($this.options.onFinish))
{
var context = { fromStep: $this.curStepIdx + 1 };
if (!$this.options.onFinish.call(this, $($this.steps), context))
{
return false;
}
}
else {
var frm = $this.target.parents('form');
if (frm && frm.length)
{
alert($scope.Clients_CW);
frm.submit();
}
}
}
return false;
});
My question and problem is... how do I pass through the $scope.Clients_CW data to the finish button method or how do I call the sendForm(data) method and it's parameter in the finish button method?
You can very well use route params to pass data between states. Refer ngRoute. You could also store the data in $rootScope or $localStorage for example to use the data in multiple states. The latter step would also work if both the files are required for the same state.

Access parameter of Node.js module function

im totally new to node.js and i couldn't find a similar question for my problem. I'm sure it's easy to solve for one of u guys... at least i guess.
I'm trying to get a special paragraph of a wikipage using the npm mediawiki module for node.js! I get the paragraph using the pre-defined function as following:
bot.page(title).complete(function (title, text, date) {
//extract section '== Check ==' from wikipage&clean string
var result = S(text).between('== Check ==', '==').s;
});
Thats working. What i want is: to use "result" outside of that code block in other functions. I think it has something to do with callbacks but im not sure how to handle it as this is a pre-defined function from the mediawiki module.
The example function of the module to get a wikipage looks as following:
/**
* Request the content of page by title
* #param title the title of the page
* #param isPriority (optional) should the request be added to the top of the request queue (defualt: false)
*/
Bot.prototype.page = function (title, isPriority) {
return _page.call(this, { titles: title }, isPriority);
};
which uses the following function of the module:
function _page(query, isPriority) {
var promise = new Promise();
query.action = "query";
query.prop = "revisions";
query.rvprop = "timestamp|content";
this.get(query, isPriority).complete(function (data) {
var pages = Object.getOwnPropertyNames(data.query.pages);
var _this = this;
pages.forEach(function (id) {
var page = data.query.pages[id];
promise._onComplete.call(_this, page.title, page.revisions[0]["*"], new Date(page.revisions[0].timestamp));
});
}).error(function (err) {
promise._onError.call(this, err);
});
return promise;
}
There's also a complete callback function and i dont know how to use it:
/**
* Sets the complete callback
* #param callback a Function to call on complete
*/
Promise.prototype.complete = function(callback){
this._onComplete = callback;
return this;
};
How can i access the "result" variable by using callbacks outside the function of the module? I don't know how to handle the callback as it is a pre-defined function of a module...
What i want is: to use "result" outside of that code block in other functions.
You can't. You need to use the result inside that code block (that code block is called a callback function btw.). You can still pass them to other functions, you just need to do it inside that callback function:
bot.page(title).complete(function (title, text, date) {
//extract section '== Check ==' from wikipage&clean string
var result = S(text).between('== Check ==', '==').s;
other_function(result); // <------------- this is how you use it
});

angular resource PUT response lost

How to I get angular to retain data updates returned in the response to a PUT?
I have a basic angular (vsn 1.2.26) RESTful app that successfully retrieves, updates and writes data back to the server. The server alters the "updateTime" field of the updated record and returns it in the (200) response to the browser. I can see the updated value in the $resource.save callback function, but I can't figure how to persist it to the $scope beyond the duration of the callback to make it visible in the UI.
angular.module('myResources',['ngResource'])
.factory('Fund',['$resource',function($resource)
{
return $resource('http://myhost/xyz/fund/:id'
,{ id: '#guid' }
,{ save: { method: 'PUT' }
,query: {method: 'GET', isArray: false }
}
);
}])
...
$scope.selectRecord = function(R)
{
...
$scope.record = R;
}
$scope.saveRecordChanges = function()
{
...
myFundResource.save($scope.record,function(response){
$scope.record = angular.fromJson(response); // gets refreshed data but doesn't update UI
console.log("new updateTime=" + $scope.record.updateTime); // correctly displays new value in the log
});
}
You can add this to your save callback function:
$scope.$apply();
Or you can change you function into:
$scope.saveRecordChanges= function(){
myFundResponse.save($scope.record).$promise.then(function(response){
$scope.record = response;
});
};
Cuz in angular $promise, it will invoke $asyncEval to call your success or error callback, which means with angular $promise will update the view automatically.
My error was that I was expecting the ng-repeat record list to update - but I wasn't updating the list, only redirecting the $scope.record (current record) pointer to a new object. I added code to update the record list:
myFundResource.save($scope.record,function(response)
{
var vIdx = $scope.allRecords.indexOf($scope.record); // allRecords is bound to the UI table via ng-repeat
$scope.record = response; // ** $scope.record no longer points to the same object as $scope.allRecords[vIdx] - array is unaware of this change
$scope.allRecords[vIdx] = $scope.record; // replace array element with new object
});
Thank you to #Tyler.z.yang for your insights and questions that got me thinking in the right direction.

delaying instantiation of a view until value exists

The get function in Backbone does not seem to take a success callback. Is there a way to delay the creation of the view in the code below until I'm sure self.restaurant exists?
self.restaurant = app.collections.restaurants.get(id);
this.showView( '#main', new app.Views.RestaurantDetailView({model: self.restaurant }) );
I can do this
if (self.restaurant){
this.showView( '#main', new app.Views.RestaurantDetailView({model: self.restaurant }) );
}else{
}
but if self.restaurant doesn't exist then I end up doing something awkward to make it work. I'm thinking there must be an simple solution to this problem that I don't know.
Instead of calling get on the collection with the id, I rather created a new model with the id, and then called fetch on the model. Fetch takes a success callback so there's no issue of waiting until the query's finished before creating the view
var restaurant = new app.Models.Restaurant({ id: id });
var self = this;
restaurant.fetch({
success:function () {
self.showView( '#restaurants', new app.Views.RestaurantDetailView({model: restaurant}) );
}
});

backbone js before and after save events

We need to be able handle the before and after save events from backbone.
Basically, when we have a load of saves happening we'd like to show a "Saving..." message. Not sure how Backbine handles batches of saves but if there is a queue we'd like to be able to show before the batch is processed and then remove after it is finished.
Is there anything like this in Backbone?
Before you call save, just show your message. So there's the before case.
As for the after, you can pass in success function. The save method takes 2 optional parameters. The only caveat is that the first always has to be attributes.
yourModel.save({
attr1: attr1,
attr2: attr2
},
{
success: function(model, response)
{
//do whatever
}
});
How about overriding Backbone.Model.save? Quick'n'dirty implementation:
Backbone.Model._amountOfModelsSaving = 0;
Backbone.Model._save = Backbone.Model.save;
Backbone.Model.save = function() {
if ( Backbone.Model._amountOfModelsSaving === 0 ) {
// Show the message
}
Backbone.Model._amountOfModelsSaving++;
var request = Backbone.Model._save.apply( this, arguments );
request.always( function() {
Backbone.Model._amountOfModelsSaving--;
if ( Backbone.Model._amountOfModelsSaving === 0 ) {
// Hide the message
}
});
return request;
}

Categories

Resources