Win8 JS App: How can one prevent backward navigation? Can't set WinJS.Navigation.canGoBack - windows-8

Fairly new to developing for Windows 8, I'm working on an app that has a rather flat model. I have looked and looked, but can't seem to find a clear answer on how to set a WinJS page to prevent backward navigation. I have tried digging into the API, but it doesn't say anything on the matter.
The code I'm attempting to use is
WinJS.Navigation.canGoBack = false;
No luck, it keeps complaining about the property being read only, however, there are no setter methods to change it.
Thanks ahead of time,
~Sean

canGoBack does only have a getter (defined in base.js), and it reflects the absence or presence of the backstack; namely nav.history.backstack.
The appearance of the button itself is controlled by the disabled attribute on the associated button DOM object, which in turn is part of a CSS selector controlling visibility. So if you do tinker with the display of the Back button yourself be aware that the navigation plumbing is doing the same.
Setting the backstack explicitly is possible; there's a sample the Navigation and Navigation History Sample that includes restoring a history as well as preventing navigation using beforenavigate, with the following code:
// in ready
WinJS.Navigation.addEventListener("beforenavigate", this.beforenavigate);
//
beforenavigate: function (eventObject) {
// This function gives you a chance to veto navigation. This demonstrates that capability
if (this.shouldPreventNavigation) {
WinJS.log && WinJS.log("Navigation to " + eventObject.detail.location + " was prevented", "sample", "status");
eventObject.preventDefault();
}
},

You can't change canGoBack, but you can disable the button to hide it and free the history stack.
// disabling and hiding backbutton
document.querySelector(".win-backbutton").disabled = true;
// freeing navigation stack
WinJS.Navigation.history.backStack = [];
This will prevent going backward and still allow going forward.

So lots of searching and attempting different methods of disabling the Back Button, finally found a decent solution. It has been adapted from another stackoverflow question.
Original algorithm: How to Get Element By Class in JavaScript?
MY SOLUTION
At the beginning of a fragment page, right as the page definition starts declaring the ready: function, I used an adapted version of the above algorithm and used the resulting element selection to set the disabled attribute.
// Retrieve Generated Back Button
var elems = document.getElementsByTagName('*'), i;
for (i in elems)
{
if((" "+elems[i].className+" ").indexOf("win-backbutton") > -1)
{
var d = elems[i];
}
}
// Disable the back button
d.setAttribute("disabled", "disabled");
The code gets all elements from the page's DOM and filters it for the generated back button. When the proper element is found, it is assigned to a variable and from there we can set the disabled property.
I couldn't find a lot of documentation on working around the default navigation in a WinJS Navigation app, so here are some methods that failed (for reference purposes):
Getting the element by class and setting | May have failed from doing it wrong, as I have little experience with HTML and javascript.
Using the above method, but setting the attribute within the for loop breaks the app and causes it to freeze for unknown reasons.
Setting the attribute in the default.js before the navigation is finished. | The javascript calls would fail to recognize either methods called or DOM elements, presumably due to initialization state of the page.
There were a few others, but I think there must be a better way to go about retrieving the element after a page loads. If anyone can enlighten me, I would be most grateful.
~Sean R.

Related

Cycle.js/xstream click event streamed once, but fired twice

There's a single button element on the page and the following click stream:
let submitClick$ = sources.DOM.select(buttonSel)
.events("click")
.mapTo(true)
.debug(console.log)
Once I click on the button, true is logged, which is correct.
However, when I map the stream, the code inside runs twice:
let submitDeal$ = submitClick$.map(() => {
console.log("Clicked")
// ...
})
No other event handlers should be attached to the button, and the element itself sits inside a div:
button(".btn--add", "Submit")
The usual event.preventDefault() and event.stopPropagation() doesn't make a difference, and inspecting the event does show that it is fired from the same element button.btn--add.
Not really sure what's going on, any ideas are appreciated! Thanks!
Versions:
"#cycle/dom": "^12.2.5"
"#cycle/http": "^11.0.1"
"#cycle/xstream-run": "^3.1.0"
"xstream": "^6.4.0"
Update 1: I triple checked and no JS files are loaded twice. I'm using Webpack that bundles a single app.js file that's loaded on the page (Elixir/Phoenix app). Also when inspecting the button in the Event Listeners tab in Chrome's Developer Tools, it seems that only 1 event handled is attached.
Update 2: Gist with the code
Too little information is given to resolve this problem. However some things come to mind:
You shouldn't use .debug(console.log) but .debug(x => console.log(x)) instead. In fact .debug() is enough, it will use console.log internally.
Then, is the button inside a <form>? That may be affecting the events. In general this question needs more details.
Turns out this was due to a bug in xstream, which was fixed in xstream#7.0.0.

Is it possible to HIDE Javascript Object's prototype! What's the MYSTERY behind this?

I'm using openui5. There is a constructor Function for UI control Button,unable to see the prototype properties of the Button but the same thing when executed in browser console, shows up!
sap.m.Button.prototype.Move = function(){
console.log('Move');
}
var oButton = new sap.m.Button({text:"Hello"});
oButton.Move(); // throws undefined function!
The same code when executed browser in console, it works!
jsbin --> http://jsbin.com/tepum/1/edit
After running the code I find that creating the first instance of sap.m.Button causes script to change the prototype of sap.m.Button. It's valid in JavaScript but not very smart if you ask me.
A first creation causes a synchronous request (no no as well) to fetch library-parameters.json.
If you run the code the second time it will have prototype.move because creating an instance of Button will not change the Button.prototype.
The capital M in Move would suggest a constructor function so I would advice changing it to lower case.
Since fetching the parameters is synchronous you can create the first instance and then set the prototype:
console.log("First Button creation changes Button.prototype");
var oButton = new sap.m.Button({text:"Hello"});
sap.m.Button.prototype.move = function(){
console.log('Move');
}
oButton.placeAt('content');
oButton.move(); // logs Move
My guess is that this is done to lazy load controls, if a Button is never created then the json config files are never loaded for these unused controls. It has a couple of drawbacks though.
You have to create an instance first before you can set the prototype.
The config files are synchronously loaded so when creating first instance of many controls with a slow connection would cause the app to be unresponsive.
A better way would be for a factory function to return a promise so you create the control the same way every time and the config files can be fetched asynchronously.
[update]
Looking at the config it seems to be config for the whole gui library so I can't see any reason why this is loaded only after creating a first instance. A library that changes it's object definitions when creating instances is not very easy to extend because it's unpredictable. If it only changes prototype on first creation then it should be fine but it looks like the makers of the library didn't want people to extend it or they would not make the object definition unpredictable. If there is an api documentation available then maybe try to check that.
[update]
It seems the "correct" way to extend controls is to use extend.
#HMR is right the correct way to extend a control is by using the extend function provided by UI5 managed objects, see http://jsbin.com/linob/1/edit
in the example below when debugging as mentoned by others you will notice that the control is lazy loaded when required, any changes you make prior are lost when loaded
jQuery.sap.declare("my.Button");
jQuery.sap.require("sap.m.Button");
sap.m.Button.extend("my.Button", {
renderer: {}
});
my.Button.prototype.Move = function() {
console.log('Move');
};
var oButton = new my.Button({
text: "Hello"
});
oButton.placeAt('content');
oButton.Move();
It's not hiding the prototype per se. If a constructor function exits normally then you get that function's prototype. But, if a constructor function actually returns some other object then you get that other object's prototype, so it's not valid to assume that just because you added to the Button prototype that when you call new Button() that you will see your method on whatever you get back. I'm sure if you de-obfuscate that code you'll find that the constructor you are calling has a "return new SomeOtherInstanceOfButton()" or similar at the end of it.
Edit: Ok it's a bit difficult to see what's really going on in that sap code but, it looks like they have code that overwrites the prototypes of controls to add features to them, such as: sap.ui.core.EnabledPropagator, and those things aren't run until you actually instantiate a button. So if you change your code to instantiate the button on the page, then add to it's prototype, then construct and call the method, it works fine. Like so:
http://jsbin.com/benajuko/2/edit
So I guess my answer is, when you run it from console it's finished mucking around with that prototype, whereas in your test you were adding to the prototype, then constructing the button for the first time (which changes the prototype again) then trying to call your old one, which is no longer there.

Lazy Load - refresh / update when combined with javascript filtering

I am now trying to implement lazyload onto my website.
I have successfully got lazy load working on pages that have a static gallery.
The main portfolio of the website has a large list of images that can be filtered using the javascript library Isotope.
The lazy load works fine when filtering is not in used, however, if the page loads and I don't scroll, but filtering is used, the items which are brought into view don't resolve. I found that occasional images worked, but most don't.
Any suggestions on how to fix this?
Presumably i need to be able to do something that will re-trigger lazy load to refresh or recheck itself?
Here is the gallery I am trying to get working, where you can see the issues I am having: http://www.imageworkshop.com/lazyload-portfolio/
Anyone able to help?
call this code on filtered item is clicked: $(window).trigger('scroll');
I found this answer from acarabott - https://stackoverflow.com/a/13919010/735369
I have implemented this and this has worked.
The only issue is that the refresh doesn't happen until a scroll action takes place.
If you want to use isotope's sorting/filtering functions, you will need to set the failure_limit of lazyload and trigger the event with isotope's onLayout callback.
jQuery(document).ready(function($) {
var $win = $(window),
$con = $('#container'),
$imgs = $("img.lazy");
$con.isotope({
onLayout: function() {
$win.trigger("scroll");
}
});
$imgs.lazyload({
failure_limit: Math.max($imgs.length - 1, 0)
});
Explanation
According to the docs ( http://www.appelsiini.net/projects/lazyload )
After scrolling page Lazy Load loops though unloaded images. In loop it checks if image has become visible. By default loop is stopped when first image below the fold (not visible) is found. This is based on following assumption. Order of images on page is same as order of images in HTML code. With some layouts assumption this might be wrong.
With an isotope sorted/filtered list, the page order is certainly different from the HTML so we need to adjust our failure_limit.
As you can see we store the jQuery object so that we can use its length-1 as our failure_limit. If you're curious as to why it is length-1, it's because of the following check in lazyload's update method.
if (++counter > settings.failure_limit) {
return false;
}
Lazy load on other events
If you are not triggering your lazyloads on scroll, you will need to swap the "scroll" trigger for whichever event you are using.
Demo
http://jsfiddle.net/arthurc/ZnEhn/

Existing widgets not available in a widget template in some (strange) cases

This took me a while. A long while. I battled two problems at once (circular dependencies, fixed with refactoring, and this problem). To get this problem into a JSFiddle required a LOT of work... but I think it was worth it.
So:
http://jsfiddle.net/EVbTL/3/
I define three widgets:
r.AppMainScreen -- This is the main app's widget. Easy: just a bunch of tabs, and a button which contains a simple button, which goes:
// SUbmit form
this.form.onSubmit = function(e){
e.preventDefault();
console.log("HERE");
dialog = new r.RetypePasswordDialog();
dialog.show();
return false;
}
Pretty uninteresting.
r.RetypePasswordDialog() -- A templated widget which represents a dialog box. The only interesting thing about it is:
< input name="password" id="${id}_password" data-dojo-attach-point="password" data-dojo-type="app.ValidationPassword" />
It's a simple custom widget, defined in this very file, which does validation. NOTE: I know there is no point in having a subclass here for this little work. Please keep in mind that this is an example.
r.ValidationPassword()
An augmented ValidationTextBox with some extra validation.
If you click on the button, you get:
Uncaught Error: Could not load class 'app.ValidationPassword
...?!? app.ValidationPassword has definitely been defined. It ought to be available there. At the beginning, I thought it was because of aa circular dependency (it was very fun, yesterday: I had to learn about AMD circular dependencies WHILE trying to figure out this problem...)
If you uncomment this line, executed within the script:
TEST = new r.RetypePasswordDialog();
The whole thing works. It's a meaningless instance, and I cannot figure out why on earth this would or should make a difference.
Explanations most welcome... I couldn't find any!
Thank you,
Merc.
app = new r.AppMainScreen( {});
You redefine the global app variable here, but are trying to use it elsewhere as the base object for your type system. Use var to scope variables to the function.

Chrome Extension Dev: Updating javascript variables in background.html

I have a working extension, and now I'm trying to add some options/features!
I have a background page which keeps track of the "state" of each tab (per tab javascript variables that hold options/settings). Now I want to have a popup.html file which will have 1 option, a time slider. I'm not concerned with the slider or any html/css. My issue is that I'm unsure of how to communicate the new setting to the background page.
My background page contains some code like this:
chrome.browserAction.onClicked.addListener(function(tab) {
Init(tab);
});
...
function Init(tab)
{
chrome.tabs.sendRequest(tab.id,
{
'TurnOffTimer': false,
'TimerIsOn': TimerIsOn,
'Interval': Interval,
'RefreshRate': RefreshRate
}, responseCallback);
}
TimerIsOn, Interval, and RefreshRate are javascript variables on the same page.
What I need to know is how, once the slider (which is declared in the popup.html) is set and the user clicks 'ok', the timer value can be sent to background.html to be stored in the appropriate javascript variable, and the extension functionality can be updated. I can create another function called Update which will take this updated value and run, but I need to know how I can call the Update function from popup.html if it's declared in background.html.
Hopefully I'm making sense but if clarification is necessary, feel free to ask.
You can directly access background page's window object from popup with chrome.extension.getBackgroundPage(). So to change some var in bg page from popup you can just call:
chrome.extension.getBackgroundPage().Interval = 5;
You would need to change your extension a bit, as once you have popup attached to browser action button, chrome.browserAction.onClicked listener won't be firing anymore. You would need to call Init from popup manually in a similar way:
chrome.extension.getBackgroundPage().Init();
And inside Init() manually get selected tab id, as it won't be passed anymore.