Calling Store from App.JS - extjs

I am in the app.js file. there is a function that gets executed when user logs in to the stytem successfully;
loginSuccess: function() {
this.getViewport().getLayout().setActiveItem(1).store.load(); // Calls the Store of the i need to navigate
this.getViewport().getLayout().setActiveItem(1); // The view i will be navigating
}
I am getting an error stating this.getViewport().getLayout().setActiveItem(1).store is undefined. i think i'm calling the Store the wrong way. how could i correct this ? How can i call the Store from the app.js ?
UPDATE
var st = Ext.getStore('myStore');
st.load();
st.on('load', function() {
this.getViewport().getLayout().setActiveItem(1);
});

Correct way to initiate store loading is:
var st = Ext.getStore('MyStore');
st.load();
just remember that loading is async process, so if you want something to be executed after store is loaded you can't just write a code after load() - you would need to subscribe to the load event.

Related

How to assign scope variable inside function that returns data from server?

I have a function that is in angular controller.
scope.asyncInit is called at the end of controller. It is a function that inits data for view.
scope.asyncInit = function() {
scope.phoneData;
dsc.In('module-agreements-lists').run('select_agreements_by_value').now('phone').then(function(res) {
scope.phoneData = res.result;
});
};
I should return data from database and asing it to scope.phoneData variable.
The problem is that when i use it like this:
scope.asyncInit = function() {
scope.phoneData;
dsc.In('module-agreements-lists').run('select_agreements_by_value').now('phone').then(function(res) {
scope.phoneData = res.result;
console.log(scope.phoneData);
});
};
It shows the data that are returned from the server in console log but they are not visible outside the dsc.In('module-agreements-lists').run('select_agreements_by_value').now('phone').then(function(res) ....
The console log that's in the code below returns to console log scope.phoneData as undefined.
scope.asyncInit = function() {
scope.phoneData;
dsc.In('module-agreements-lists').run('select_agreements_by_value').now('phone').then(function(res) {
scope.phoneData = res.result;
});
console.log(scope.phoneData);
};
Am i missing something important here? I have no idea why it's not working properly.
It is because that is an Asynchronous call.
An asynchronous call to the server will just run, and not wait for success.
So the code goes on, even if you did not get the data yet.
You use .then() function to do stuff that you want to be called after success.
Thats why it logs 'undefined' in the second method. The data did not arrive from the server yet.

Login ajax request Flux React?

How can I do
after login form submit (React Component)
using flux structure
ajax request that provides response ?
Can you provide some example ?
Basically you need to make an Ajax request, and then create success/error handlers. Inside those handlers, you will create actions to inform your stores of the result. It's probably a good idea to have an AppStore or SessionStore or something that will hold the data related to the current user and the auth token. Your controller-views can listen to that store and render their children when the current user becomes authenticated.
Here's how i made:
When my component bootstraps, I fire an INIT action to the Store which initially gets the datas i need. Here's the simplified data flow
After login my Library component is rendered so i need to initialize the data (books, users etc..)
Library:
componentDidMount: function() {
Store.addChangeListener(this._onChange);
Actions.initialize();
},
As you can see, when my component did mount, i fired a new action, and my store will handle this action.
Store:
switch(action.actionType) {
case Constants.INIT:
_init().done(function() {
Store.emitChange();
});
break;
I'm calling the private function _init() which will return a promise object. When the promise is Fulfilled the Store is ready to emit it's change event.
In _init I'm simulating some async data loads, thats why i made the promise, here it is:
function _init() {
var loadBooksDeferred = new jQuery.Deferred(),
loadUsersDeferred = new jQuery.Deferred(),
loadCategoriesDeferred = new jQuery.Deferred(),
stateReadyDfd = new jQuery.Deferred();
_loadBooks(loadBooksDeferred);
_loadUsers(loadUsersDeferred);
_loadCategories(loadCategoriesDeferred);
jQuery
.when(loadBooksDeferred, loadUsersDeferred, loadCategoriesDeferred)
.then(stateReadyDfd.resolve, stateReadyDfd.reject);
return stateReadyDfd;
}

angularfireCollection: know when the data is fully loaded

I am writing a small Angular web application and have run into problems when it comes to loading the data. I am using Firebase as datasource and found the AngularFire project which sounded nice. However, I am having trouble controlling the way the data is being displayed.
At first I tried using the regular implicit synchronization by doing:
angularFire(ref, $scope, 'items');
It worked fine and all the data was displayed when I used the model $items in my view. However, when the data is arriving from the Firebase data source it is not formatted in a way that the view supports, so I need to do some additional structural changes to the data before it is displayed. Problem is, I won't know when the data has been fully loaded. I tried assigning a $watch to the $items, but it was called too early.
So, I moved on and tried to use the angularfireCollection instead:
$scope.items = angularFireCollection(new Firebase(url), optionalCallbackOnInitialLoad);
The documentation isn't quite clear what the "optionalCallbackOnInitialLoad" does and when it is called, but trying to access the first item in the $items collection will throw an error ("Uncaught TypeError: Cannot read property '0' of undefined").
I tried adding a button and in the button's click handler I logged the content of the first item in the $items, and it worked:
console.log($scope.items[0]);
There it was! The first object from my Firebase was displayed without any errors ... only problem is that I had to click a button to get there.
So, does anyone know how I can know when all the data has been loaded and then assign it to a $scope variable to be displayed in my view? Or is there another way?
My controller:
app.controller('MyController', ['$scope', 'angularFireCollection',
function MyController($scope, angularFireCollection) {
$scope.start = function()
{
var ref = new Firebase('https://url.firebaseio.com/days');
console.log("start");
console.log("before load?");
$scope.items = angularFireCollection(ref, function()
{
console.log("loaded?");
console.log($scope.items[0]); //undefined
});
console.log("start() out");
};
$scope.start();
//wait for changes
$scope.$watch('items', function() {
console.log("items watch");
console.log($scope.items[0]); //undefined
});
$scope.testData = function()
{
console.log($scope.items[0].properties); //not undefined
};
}
]);
My view:
<button ng-click="testData()">Is the data loaded yet?</button>
Thanks in advance!
So, does anyone know how I can know when all the data has been loaded
and then assign it to a $scope variable to be displayed in my view? Or
is there another way?
Remember that all Firebase calls are asynchronous. Many of your problems are occurring because you're trying to access elements that don't exist yet. The reason the button click worked for you is because you clicked the button (and accessed the elements) after they had been successfully loaded.
In the case of the optionalCallbackOnInitialLoad, this is a function that will be executed once the initial load of the angularFireCollection is finished. As the name implies, it's optional, meaning that you don't have to provide a callback function if you don't want to.
You can either use this and specify a function to be executed after it's loaded, or you can use $q promises or another promise library of your liking. I'm partial to kriskowal's Q myself. I'd suggest reading up a bit on asynchronous JavaScript so you get a deeper understanding of some of these issues.
Be wary that this:
$scope.items = angularFireCollection(ref, function()
{
console.log("loaded?");
console.log($scope.items[0]); //undefined
});
does correctly specify a callback function, but $scope.items doesn't get assigned until after you've ran the callback. So, it still won't exist.
If you just want to see when $scope.items has been loaded, you could try something like this:
$scope.$watch('items', function (items) {
console.log(items)
});
In my project I needed to know too when the data has been loaded. I used the following approach (implicit bindings):
$scope.auctionsDiscoveryPromise = angularFire(firebaseReference.getInstance() + "/auctionlist", $scope, 'auctionlist', []);
$scope.auctionsDiscoveryPromise.then(function() {
console.log("AuctionsDiscoverController auctionsDiscoveryPromise resolved");
$timeout(function() {
$scope.$broadcast("AUCTION_INIT");
}, 500);
}, function() {
console.error("AuctionsDiscoverController auctionsDiscoveryPromise rejected");
});
When the $scope.auctionsDiscoveryPromise promise has been resolved I'm broadcasting an event AUCTION_INIT which is being listened in my directives. I use a short timeout just in case some services or directives haven't been initialized yet.
I'm using this if it would help anyone:
function getAll(items) {
var deferred = $q.defer();
var dataRef = new Firebase(baseUrl + items);
var returnData = angularFireCollection(dataRef, function(data){
deferred.resolve(data.val());
});
return deferred.promise;
}

Backbone render after initialize - initialize get's triggered to early?

I have a div#game.
In here I want some data from the server to appear.
So when I use the initialize function I request data from my server in my game model with an ajax call.
Game = Backbone.View.extend(
{
id: 'game',
initialize: function ()
{
this.model.on('getGame', function() {});
this.model.getGame();
}
}
Because a callback doesn't seem to work in backbone a trigger has to be made.
So the app listens to the trigger getGame which is triggerd when the data from the server has been returned and saved into a variable in the model.
So far so good, this all works. The only problem now is that I want my div#game to fadeIn when it's done appending all data from the getGame function.
But I think because off the model.on(trigger) the initialize function 'thinks' it's ready after running the getGame() function, without actually having the data from the server appended yet.
So the parent div#all running the following:
this.$el.append(new Game().el);
also 'thinks' the div#game is ready and appends the div#game to itself and gives it a fadeIn.
div#game doesn't contain the server data yet, so when it actually does come back the images and text pop into existence instead of fadeIn in nicely...
Does some one know how to resolve this problem?
Thanks in advance!
======================================================
SOLVED
The problem was in the asynchronous property of the $.get and $.post functions. This is why the initialize was ready before the results had come back from the server. I changed it into a $.ajax and made the async: false. Now it all loads in the order I programmed/want.
Thank you for your detaild explaination Tallmaris, it will come in handy for sure since I'll be using a lot of triggers!
Rather than having the div#all render and append the view to itself, you can pass it as a parent to the View:
this.gameView = new Game({parent: this});
Then in your Game view:
initialize: function (options)
this.parent = options.parent
{
this.model.on('getGame', function() { this.$el.appendTo(this.parent); });
this.model.getGame();
}
Alternatively you could use a global Backbone event object like this:
window.vent = $.extend({}, Backbone.Events);
Now you have a global object (which you can name and put in any namespace as you like, don't just do it as in the code above), that you can use like this:
MAIN VIEW:
initialize: function () {
vent.on("GameReady", function ()
{
// fade in game view
});
}
GAME VIEW:
initialize: function (options)
this.parent = options.parent
{
this.model.on('getGame', function() { vent.trigger("GameReady"); });
this.model.getGame();
}
You can also pass parameters around. Read here for more documentation.

EXTJS Store load callback issue

I load my store as follows:
store.load({
params: {
paramMap
},
callback: function(records, options, success) {
if (success) {
var form = formPanel.getForm();
var jsonStr = Ext.JSON.encode(records[0].raw);
var jsonObj = Ext.JSON.decode(jsonStr);
form.loadRecord(jsonObj);
}
}
});
The thing is I only want this call back to fire the first time the store is loaded. I want to remove it after that so that when I reload or load the store again it doesn't call this callback again.
Any idea, I tried getting the callback in the options config but that doesn't seem to work.
Not exactly sure what the problem is. The callback will only get called when the store is loaded with the callback.
store.load({callback:myCallback});
//callback will be called
store.load();
//callback will not be called
If you want to just do something once you might want to use a listener with single set to true. Listeners instead of callbacks is my preferred way.
store.on('load', onStoreLoad, this, {single:true});
The callback function arguments api is slightly different than a load listener, check the docs to see.

Resources