Overriding back button in android - Phonegap Angularjs - angularjs

I have following as my index.js (used to initialize phonegap)
function onBackKeyDown() {
angular.element('[ng-controller=NavCtrl]').scope().back();
}
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('load', this.onLoad, false);
document.addEventListener('deviceready', this.onDeviceReady, false);
window.addEventListener("orientationchange", orientationChange, true);
},
onLoad: function() {
},
onDeviceReady: function() {
document.addEventListener("backbutton", onBackKeyDown, false);
}
};
This should technically run the function onBackKeyDown when back button is pressed which it does. I can see the logs in logcat.
This as per the documentation should override the default behavior, but apparently when i click back button it not only fires the function but executes the default behavior as well.
I am taken back to my login screen, whereas the behavior described is something else.
Please can anyone point me to the right direction, and let me know what I am not doing correct.

Not sure if it will do the trick but you could check if the onBackKeyDown function get an event as first parameter. If yes then try something like :
function onBackKeyDown(evt) {
evt.preventDefault();
evt.stopPropagation();
angular.element('[ng-controller=NavCtrl]').scope().back();
}

Related

Ext.form.Panel's beforesubmit listener does not respect return: false when attached via controller

I have a formpanel with a beforesubmit listener, which should prevent the submission if the form is invalid.
Sencha Fiddle availble here:
https://fiddle.sencha.com/#fiddle/3j5l (just comment the beforesubmit: 'onFormBeforeSubmit' line within the controler/panel and inspect the console to see the difference)
The listener is attached via a controller trough the init function like this:
//controller init function
init: function () {
var me = this;
me.listen({
component: {
'formpanel': {
beforesubmit: 'onFormBeforeSubmit'
}
}
});
},
onFormBeforeSubmit: function () {
console.log(arguments);
var me = this, form = me.getView();
console.log('beforesublit event fired');
if (!form.validate()) {
console.log('form is invalid!');
return false;
}
}
And all seems fine - the submit procedure is started, the onFormBeforeSubmit() method is executed, the form is considered invalid, but althought there is a return false statement - the form is submitted to the server.
Then, i tried to attach the listener simply via the listeners config of the panel like this:
//panel definitions...
listeners: {
beforesubmit: 'onFormBeforeSubmit'
}
And then it worked as expected.
As you can see the executed function is the same.
One thing i mentioned is that it receives different arguments - if triggered via the listeners config - it has a 5 arguments. Via controller - they are 4. The 5th one is an obect like this:
beforesubmit: "onFormBeforeSubmit"
scope: "self"
Can someone explain me why is this? Is it a bug or an expected behavior?
And after all - where is the right place to attach the listeners - in the controller or within the view??
Thanks.
First of all, you don't have to do this in init function.
Simply use control block of your viewcontroller like this:
control: {
formpanel: {
beforesubmit: 'onFormBeforeSubmit'
}
},
Please refer the documentation of control, it is much more straightforward to use that.
But it still not enough, and I think you are right, this is a bug. FormPanel's submit actually still using already deprecated function to fire events.
Please try the following override, it should fix this and allows you to use event listeners defined in controllers:
Ext.define('FixPanelEventFiring',{
override: 'Ext.form.Panel',
submit: function(options, e) {
var me = this,
formValues, form;
options = options || {};
formValues = me.getSubmitValues({
enabled: me.getStandardSubmit() || !options.submitDisabled
});
form = me.element.dom || {};
if (this.getEnableSubmissionForm()) {
form = this.createSubmissionForm(form, formValues);
}
options = Ext.apply({
url: me.getUrl() || form.action,
submit: false,
form: form,
method: me.getMethod() || form.method || 'post',
autoAbort: false,
params: null,
waitMsg: null,
headers: null,
success: null,
failure: null
}, options || {});
return me.fireEventedAction('submit',
[me, formValues, options, e],
'doBeforeSubmit',
this,
null,
'after'
);
},
});
Please be sure you include this in your overrides. You can also test this in fiddle, just add it before everything else. I'm not 100% sure it is perfect, I can imagine there are other issues with this, so please test this well.

Backbone trigger event after custom function possible?

Excuse my backbone i'm not an expert, Must execute function Show absolutely and only after ResetQuestions
ResetQuestions:function () {
//Great Code Here
}),
I tried this:
initialize: function () {
this.on("Show", this.Show, this);
},
ResetQuestions:function () {
//Great Code Here
this.trigger("Show");
}),
But that was unsuccessful, does anyone know how i can accomplish this?
no need of events you can simply call the function from other function
var sampleView = Backbone.View.extend({
initialize: function () {
this.ResetQuestions();
},
Show: function () {
alert('i am at show');
},
ResetQuestions: function () {
// Execute all you code atlast call Show function as below.
this.Show();
}
});
var view = new sampleView();
var sampleView = Backbone.View.extend({
initialize: function(){
this.ResetQuestions().promise().done(function() { // Using promise here.
this.Show();
});
},
Show: function(){
},
ResetQuestions: function(){
// Execute all you code atlast call Show function as below.
}
});
Then initiate your view,
var view = new sampleView();
Hope this works!!
Perhaps you just got confused what runs what and by naming event and method with same name Show. I have created a jsfiddle with your code - http://jsfiddle.net/yuraji/aqymbeyy/ - you call ResetQuestion method, it triggers Show event, and the Show event runs Show method.
EDIT: I have updated the fiddle to demonstrate that you probably have to bind the methods to the instance, I used _.bindAll for that. If you don't do that you may get event as the context (this).
EDIT: Then, if your ResetQuestions runs asynchronous code, like an ajax request to get new questions, you will have to make sure that your Show event is triggered when the request is completed.

How to test if an event handler is set in a Marionette.js view?

There is a Marionette.js view which acts as a login form. The following code sample shows the relevant code parts including an error I already fixed:
MyApp.module("User", function(User, App, Backbone, Marionette, $, _) {
User.LoginView = Marionette.ItemView.extend({
className: "reveal-modal",
template: "user/login",
ui: {
signInForm: "#signin-form"
},
events: {
"submit #signin-form": "onSignInFormSubmit"
},
onRender: function() {
var self = this;
var $el = this.$el;
// [...] Render schema
_.defer(function(){
$el.reveal({
closeOnBackgroundClick: false,
closed: function(){
self.close(); // <-- This is incorrect. Do not close the ItemView directly!
}
});
});
},
onSignInFormSubmit: function(event) {
event.preventDefault();
var errors = this.signInForm.validate();
var data = this.signInForm.getValue();
// [...] Notify that data has been submitted.
},
hideForm: function() {
this.$el.trigger("reveal:close");
}
});
});
I noticed a major mistake in my implementation. In the callback function closed of Reveal I decided to close the ItemView directly which is wrong as you can read in the documentation of Marionette.js:
View implements a close method, which is called by the region managers automatically.
Bugfix: Instead close() should be called on the region. I fixed this error.
Now I ask myself how can I actually write a test which covers the problem. I use Jasmine for testing. I noticed that the event handler onSignInFormSubmit is no longer called after I have incorrectly closed the ItemView and try to re-submit the form.
Here is a first draft of the test which unfortunately does fail also with the bugfix:
it("should call the submit handler for the sign-in form", function() {
spyOn(userController.loginView, "onSignInFormSubmit");
spyOn(userController.loginView.signInForm, "validate").andCallFake(function(params) {
return null;
});
userController.loginView.hideForm();
userController.loginView.ui.signInForm.trigger("submit");
expect(userController.loginView.onSignInFormSubmit).toHaveBeenCalled();
});
Maybe one could also test if the event handler is registered such as:
expect(userController.loginView.events["submit #signin-form"]).toEqual("onSignInFormSubmit");

Backbone event being called multiple times

I'm just getting my feet wet with Backbone, and I think I have an easy problem to solve. I have the following view which is a simple tab that when clicked opens up a panel and when closed goes back to a tab:
myApp.views.Support = {
Form: Backbone.View.extend({
initialize: function () {
this.el = $('#support');
this._ensureElement();
},
render: function () {
if (this.$el.hasClass('support-panel')) {
// close panel
this.$el.empty();
this.$el.removeClass('support-panel');
this.$el.addClass('support-button');
}
else {
// open and populate panel
var template = _.template(myApp.utils.RenderTemplate('support/default'), {});
this.$el.removeClass('support-button');
this.$el.addClass('support-panel');
this.$el.html(template);
}
return this;
},
closePanel: function () {
alert('close event fired');
},
events: {
'click #SubmitFormButton': 'submitForm',
'click #CloseSupportPanel': 'closePanel'
},
submitForm: function (event) {
alert('form submitted: ' + $('#message'));
}
})
}
Everything is working fine except that "closePanel" gets fired +2 times every time the click event happens. I assume it's some sort of cleanup I'm missing but I don't know what.
Likely its because the event is bubbling up. Try returning false.
I know this is an old question but it helped me realize what my issue was. Returning false as Daniel said works, but the root cause of my issue was having the jQuery selector twice in my markup, resulting in two jQuery objects being created thus the click event fires twice.

Preventing full page reload on Backbone pushState

I'm trying to prevent full page reloads using Backbone's pushState. When I call navigate() from my view's event, I see the messages marked // 1 below, but not // 2. In addition, when I try to open the same tab, the page reloads again.
Must I stop the event myself? I tried using jQuery's preventDefault(), which does prevent the page reload, but I haven't seen this documented anywhere.
Below is my current code:
App.Router = Backbone.Router.extend({
routes:{
"analytics":"analytics"
, "realtime":"realtime"
}
, analytics:function(page) {
console.log("analytics route hit: %o", page); // 2
}
, realtime:function(page) {
console.log("realtime route hit: %o", page); // 2
}
});
App.TabSetView = Backbone.View.extend({
initialize:function() {
this.collection.bind("reset", this.render, this);
this.collection.bind("add", this.render, this);
this.collection.bind("change", this.render, this);
this.collection.bind("remove", this.render, this);
}
, events:{
'click li.realtime a': "onRealtime"
, 'click li.analytics a': "onAnalytics"
}
, render:function() {
// omitted for brevity
}
, onAnalytics:function() {
console.log("onAnalytics"); // 1
if (this.collection.activateAnalytics()) {
App.app.navigate("analytics", true);
this.render();
console.log("navigated");
} else {
console.log("do nothing"); // 1
}
}
, onRealtime:function() {
console.log("onRealtime");
if (this.collection.activateRealtime()) {
App.app.navigate("realtime", true);
this.render();
console.log("navigated");
} else {
console.log("do nothing"); // 1
}
}
});
var tabs = ...; // omitted for brevity
var tabSetView = new App.TabSetView({collection: tabs});
var App.app = new App.Router;
Backbone.history.start({pushState:true});
to stop the page reload when a user clicks a link, you have to call e.preventDefault() like you were suggesting.
MyView = Backbone.View.extend({
events: {
"click .some a": "clicked"
},
clicked: function(e){
e.preventDefault();
// do your stuff here
}
});
you're also right that this isn't documented in the backbone docs. events are handled by jQuery, though. so you can assume that any valid jQuery things you would do - such as have an e parameter to an event callback - will work with backbone's events.
as for this:
in addition, when I try to open the same tab, the page reloads again.
are you saying when a user opens a new browser tab to your site's url? if so, then there's nothing you can do about this. when the browser opens the tab it makes the request to the server to load the page.
if you're referring to a "tab" as part of your site's user interface, though, then the use of e.preventDefault() on your link / "tab" clicks should take care of that.
The answer is actually in here https://stackoverflow.com/a/9331734/985383, if you enable pushState you want links to work and not prevent them as suggested above, or well, is not just preventing them. here it is:
initializeRouter: function () {
Backbone.history.start({ pushState: true });
$(document).on('click', 'a:not([data-bypass])', function (evt) {
var href = $(this).attr('href');
var protocol = this.protocol + '//';
if (href.slice(protocol.length) !== protocol) {
evt.preventDefault();
app.router.navigate(href, true);
}
});
}
$('a').click(function(e){
e.preventDefault();
Backbone.history.navigate(e.target.pathname, {trigger: true});
});
Just a follow up to Derick answer.
It worked for me, but to keep it clean, I overwrote the Backbone.View class:
(coffeescript)
class NewBackboneView extends Backbone.View
events:
'click a' : 'pushstateClick'
pushstateClick: (event) ->
event.preventDefault()
Backbone.View = NewBackboneView
So every link from my backbone views have the prevent default.
It depends on how you've generated the HTML mark-up. It looks like you're using anchor tags (<a>), so if those anchor tag href have values or even an empty string, then you need to cancel the default browser behavior otherwise you'll get a page reload. You can cancel the default behaviour using jQuery're event.preventDefault() like you mentioned. Alternatively, if you're not concerned about progressive enhancement or SEO, then you can set your anchor tag href to # or javascript:void(0);, which will also prevent to the page from reloading. e.g.
Click me
or
Click me

Resources