I am working on a page having lot of input-controls and related divs. There are use-cases on this page where I am suppossed to show/hide the divs depending on the order of user clicking on input-controls in various follow-up screens.
Now the divs are all there in first load itself and by showing/hiding, the screen changes for the user. Now to show/hide I can use css and add view* class to .main content div depending on business logic.
ex.:
.main div{
display: none;
}
.main.view1 div.a,.main.view1 div.b,.main.view1 div.f{
display:block;
}
.main.view2 div.c,.main.view2 div.f {
display:block;
}
.main.view3 div.c,.main.view3 div.f {
display:block;
}
....etc
But this way the no. of css classes are getting unmanageable.
Please suggest if there is a better method I can use wherein it becomes easy to manage the user-flows. I think there are regions in marionette which can help me manage this. Please suggest the best way and elaborate if the answer is marionette.regions
You can model the application as a state machine to model complicated workflows.
To define a state machine:
Define all the states that your application can be in.
Define the set of actions that are allowed in each state. Each action will transition the state of the application from one state to another.
Write the business logic for each action which includes both persisting changes to the server and also changing the state of the views accordingly.
This design is similar to creating a DFA, but you can add extra behaviour according to your needs.
If this sounds too abstract, here's an example of a simple state machine.
Let's say you're building a simple login application.
Design the States and Actions
INITIAL_STATE: The user visits the page for the first time and both fields are empty. Let's say you only want to make the username visible, but not the password in this state. (Similar to the new Gmail workflow)
USERNAME_ENTRY_STATE: When the user types in the username and hits return, in this state, you want to display the username and hide the password. You can have onUsernameEntered as an action in this state.
PASSWORD_ENTRY_STATE: Now, the username view will be hidden and the password view will be shown. When the user hits return, you have to check if the usernames and passwords match. Let's call this action onPasswordEntered
AUTHENTICATED_STATE: When the server validates the username/password combination, let's say you want to show the home page. Let's call this action onAuthenticated
I have omitted handling the Authentication Failed case for now.
Design the Views:
In this case, we have the UsernameView and the PasswordView
Design the Models:
A single Auth model suffices for our example.
Design the Routes:
Check out the best practices for handling routes with Marionette. The state machine should be initialized in the login route.
Sample Pseudo-Code:
I've only shown the code relevant to managing the state machine. Rendering and event handling can be handled as usual;
var UsernameView = Backbone.View.extend({
initialize: function(options) {
this.stateMachine = options.stateMachine;
},
onUserNameEntered: function() {
username = //get username from DOM;
this.stateMachine.handleAction('onUserNameEntered', username)
},
show: function() {
//write logic to show the view
},
hide: function() {
//write logic to hide the view
}
});
var PasswordView = Backbone.View.extend({
initialize: function(options) {
this.stateMachine = options.stateMachine;
},
onPasswordEntered: function() {
password = //get password from DOM;
this.stateMachine.handleAction('onPasswordEntered', password)
},
show: function() {
//write logic to show the view
},
hide: function() {
//write logic to hide the view
}
});
Each state will have an entry function which will initialize the views and and exit function which will cleanup the views. Each state will also have functions corresponding to the valid actions in that state. For example:
var BaseState = function(options) {
this.stateMachine = options.stateMachine;
this.authModel = options.authModel;
};
var InitialState = BaseState.extend({
entry: function() {
//show the username view
// hide the password view
},
exit: function() {
//hide the username view
},
onUsernameEntered: function(attrs) {
this.authModel.set('username', attrs.username');
this.stateMachine.setState('PASSWORD_ENTRY_STATE');
}
});
Similarly, you can write code for other states.
Finally, the State Machine:
var StateMachine = function() {
this.authModel = new AuthModel;
this.usernameView = new UserNameView({stateMachine: this});
//and all the views
this.initialState = new InitialState({authModel: this.authModel, usernameView: this.usernameView});
//and similarly, all the states
this.currentState = this.initialState;
};
StateMachine.prototype = {
setState: function(stateCode) {
this.currentState.exit(); //exit from currentState;
this.currentState = this.getStateFromStateCode(stateCode);
this.currentState.entry();
},
handleAction: function(action, attrs) {
//check if action is valid for current state
if(actionValid) {
//call appropriate event handler in currentState
}
}
};
StateMachine.prototype.constructor = StateMachine;
For a simple application this seems to be an overkill. For complicated business logic, it is worth the effort. This design pattern automatically prevents cases such as double-clicking on a button, since you would have already moved on to the next state and the new state does not recognise the previous state's action.
Once you have built the state machine, other members of your team can just plug in their states and views and also can see the big picture in a single place.
Libraries such as Redux do some of the heavy-lifting shown here. So you may want to consider React + Redux + Immutable.js as well.
Related
I need to fetch events every time a view is switched, and need to pass the view to the server.
However, the old view is still set at the time the events are requested from the server.
For example, the following alerts the view I am switching from, not the new view.
var calendar = new FullCalendar.Calendar(calendarEl, {
lazyFetching: false,
events:
{
url: '/events/get-events',
extraParams: function(){
alert(calendar.view.type);
}
}
}
Switch views in the following codepen
https://codepen.io/bestrong89/pen/RwPVmdY?editors=0010
Any ideas on a workaround?
I'm trying to work out how I can display a form to a user upon their first login to my app ( to fill in profile information) after which they can proceed to the regular site.
Could anyone point me in the right direction?
Thanks
You can make the trick using app startup script:
https://devsite.googleplex.com/appmaker/settings#app_start
Assuming that you have Profile model/datasource, code in your startup script will look similar to this:
loader.suspendLoad();
var profileDs = app.datasources.Profile;
// It would be more secure to move this filtering to the server side
profileDs.query.filters.UserEmail._equals = app.user.email;
profileDs.load({
success: function() {
if (profileDs.item === null) {
app.showPage(app.pages.CreateProfile);
} else {
app.showPage(app.pages.HomePage);
}
loader.resumeLoad();
},
failure: function() {
loader.resumeLoad();
// your fallback code goes here
}
});
If profile is absolute must, I would also recommend to enforce the check in onAttach event for every page but CreateProfile (to prevent navigation by direct link):
// Profile datasource should be already loaded by startup script
// when onAttach event is fired
if (app.datasources.Profile.item === null) {
throw new Error('Invalid operation!');
}
I suggest checking the user profile upon login. If the profile is not present, display the profile form, otherwise, proceed to the regular site.
Below a typical action to test if a sap.m.Select contains an item with the name xyz and then select it.
success: function(oSelect) {
var oItems = oSelect.getItems();
$.each(oItems, function(i,v) {
if(oItems[i].getText() === "TestItemNameILikeToSelect") {
oTestOpa5TestItem = oItems[i];
}
});
if(oTestOpa5TestItem !== null) {
oSelect.setSelectedKey(oTestOpa5TestItem.getKey());
oTestOpa5TestItem.$().trigger("tap");
}
},
When I start the test run it does correctly select the proper item from the list and sets it visibly in the browser, but it does not trigger the attached event that is behind (e.g. change="onListItemChanged").
My application works fine, but I don't find a way to create a working test for it.
Thanks in advance
OPA5 has an 'Action' interface and two default implementations e.g. 'EnterText' and 'Press'. The recommended usage is to define an action block on the waitFor() options like this:
When.waitFor({
id: "myButton",
actions: new Press()
});
What you use is the 'old way' but it has some shortcomings:
success block is not synchronized with XHR requests but action is.
Sending a click/tap event to a control could require selecting some internal element. Imagine a click to nav container - there are several places you could click actually. Actions handle those details and define a standard behavior you could depend on.
It is better to encapsulate your selection logic inside a matchers block and even abstract it to a custom matcher. This way your success block will be cleaner and you could reuse the matcher in several places in your test.
OPA5 Actions
Have a look at the official UI5 Demo Kit, under samples > OPA5 > Code: Simulating user interactions on UI5 controls with OPA5, You will be able to find numerous examples of OPA 5 testing regarding general user interactions. In your case for the select:
opaTest("Should select an item in a sap.m.Select", function(Given, When, Then) {
When.waitFor({
id: "mySelect",
actions: new Press(),
success: function(oSelect) {
this.waitFor({
controlType: "sap.ui.core.Item",
matchers: [
new Ancestor(oSelect),
new Properties({ key: "Germany"})
],
actions: new Press(),
success: function() {
Opa5.assert.strictEqual(oSelect.getSelectedKey(), "Germany", "Selected Germany");
},
errorMessage: "Cannot select Germany from mySelect"
});
},
errorMessage: "Could not find mySelect"
});
});
https://sapui5.hana.ondemand.com/#/entity/sap.ui.test.Opa5/sample/sap.ui.core.sample.OpaAction/code/Opa.js
I'm trying to show a popup or a template page if user has signed in for the first time after sign up basically allowing them configure some stuff on that page before going to dashboard home, It's only needed for convenience and here is what I got (telescope code)
Router.onBeforeAction(hasCompletedChannels);
hasCompletedChannels: function() {
if(!this.ready()) return;
var user = Meteor.user();
if (user && ! userCompletedChannels(user)){
this.render('connectChannels');
} else {
this.next();
}
}
Which I don't really like because this will always run every time, I want it to run just once, And don't even execute the check function. Is it possible to detect first sign in? (After signup)
I think you could just tie it to the specific route. Right now you're tying it to the Router object (every render forces that check as you point out). So if you define your login function to send someone to a specific route after sign-in, you could just verify on that route.
The function Accounts.onLogin gives you a way to do stuff after the login.
Something like
Router.route('profile', {
path: '/profile',
onBeforeAction: function() {
// Check some stoof
// If first time logged in
// render first time template
// else
// this.next() will render the profile page
},
waitOn: function() {
return [
// some subs
];
},
data: function() {
// some data
}
});
I'm assuming that its going to get routed to a page called profile (seems to make sense). You could check for first time logged in by some attribute you use in the user object and the fields you want filled out and force a render of a different template, or a subtemplate. Check out the Iron Router guide for more ideas on ways to configure it.
Best of luck
I want to redraw a line in a line chart without reloading it (neither template nor controller) completely when navigating from country/5 to country/7. Can this be done with ui-router?
State
country/:id
Template with directive - country.html
<lineChart data="scope.someData">
Controller
onStateParamsChange => fetch data, set scope.someData
As of today, there is no official support for what you're looking for, which in UI Router parlance is considered 'dynamic parameters'. However, if you check out this experimental branch and help us out by testing and providing feedback, it will get merged to master sooner.
Set up your route/state like so:
$stateProvider.state("country", {
url: "/country/{id:int}",
params: { id: { dynamic: true } }
/* other state configuration here */
});
Then, in your controller, you can observe changes to id like so:
$stateParams.$observe("id", function(val) {
// val is the updated value of $stateParams.id
// Here's where you can do your logic to fetch new data & update $scope
});