How to navigate using nativescript-urlhandler - nativescript

I have a javascript Nativescript app (i.e., no Angular, Vue, or typescript), What I want to be able to do is receive a text with a deep-link into my app, receive the link, and then navigate to a specific page.
I've followed the nativescript-urlhandler docs and, on iOS, can receive the url, but I don't know what to do with it once I have it. That is, in my app.js file, I have:
handleOpenURL(function(appURL) {
console.log('Got the following appURL', appURL);
});
What I want to do from here would ordinarily be a
frame.topmost().navigate(navigationOptions);
call, but how can I get the app's viewModel for the resulting page, since that's loaded by main-page.js (using the standard template). That is, such navigation requests are otherwise always made from within the app where the viewModel is already set, but it's not yet set in app.js.
I've been looking for code samples but haven't found anything with straight NativeScript, so I'm posing the question to the StackOverflow-verse. Any help or insight welcome!

I was able to get this working. Yes, the
frame.topmost().navigate(navigationOptions);
works. What I did was create my own instance of the viewModel and set that as the binding context, such as ,
handleOpenURL(function (appUrl) {
var viewModel = createViewModel(); // create own instance of viewModel
viewModel.helpReq = parseUrl(appUrl.toString()); // add data from URL to viewModel
var navigationOptions = {
moduleName: './views/help-req-page',
context: { bindingContext: viewModel }
}
frame.topmost().navigate(navigationOptions);
}
Where parseUrl(), predictably, parses the url and creates an object from the various components.
If I have an empty action bar on the target page, then I automatically get a link back to my app that closes the target page cleanly.
I have this working on iOS; I have not tried Android yet.

Related

Correct use of Prism navigation service in xamarin forms

I want to confirm if I am using the prism navigation service with xamarin forms correctly. I have a master detail page, a styled navigation page and a bunch of content pages.
right now I am using the service in the following way:
var prj = await dataService.GetLwdProject(appState.SelectedProjectId);
var nparam = new NavigationParameters();
nparam.Add("Project", prj);
await NavigateTo("RootPage/StyledNavigationPage/SessionsListPage", nparam);
Where the Master detail page is the RootPage object. So expecting that when a user selects an item from this list page the correct way to the service should be:
var nparma = new NavigationParameters();
nparma.Add("Session", option);
await App.NavigateTo("RootPage/StyledNavigationPage/SessionsListPage?ProjectId=" + option.ProjectId + "/LocationListPage", nparma);
What I expect that just a LocationListPage would be added to the navigation stack, but when I use the the hardware back button on android it looks like that not only the last page was added but the whole path (all pages). So is this the correct way auto construct the desired path?
No. Navigation is always relative to where you are calling it. What you have now will navigate to the entire deep link you have created every time. Just navigate to your target NavigationPage/SessionListPage and pass your parameter. Though, you won't get a new page every time in this case, since you are navigating to the same view, but just passing different state.

How do I debug JQuery-BootGrid data api to NancyFX

Question edited:
I wrote a page with jquery-bootgrid data API.
Its should be calling with AJAX to my NancyFX REST API, but it isn't.
Client side:
I'm serving the bootgrid from a local repo:
<script src="~/scripts/jquery.bootgrid.min.js"></script>
Maybe I shouldn't be using the .min.js file but rather the open one for debugging? If so, could you walk me through what to do, or point me in the direction?
The page code is
...
data-toggle="bootgrid" data-ajax="true"
data-url="/cars/0" data-method="GET"
Server side:
I have the html page served by NancyFx and is seen ok, except for the grid which is empty. There's an API module with a breakpoint in Visual Studio (running on localhost), with the following:
Get["/cars/{status:int}?current={current}&rowCount={rowCount}"] = parameters => ...
This code is never called. How can I force the debugger to catch ANY call before the routing is checked, and show me what's coming into the server?
I'm using the chrome debugger.
The current URL is not valid by Nancy standards. We don't add query string params to the route.
You would want to write something along the lines of:
Get["/cars/{status:int}"] = parameters =>
{
var status = (int)parameters.status;
var current = (string)parameters.current.TryParse("");
var rowCount = (int)parameters.current.TryParse(10);
...
}
Along those lines. (written off the top of my head)
An alternative approach is to bind the request like so:
Get["/cars/{status:int}"] = parameters =>
{
var request = this.Bind<MyRequest>();
...
}
public class MyRequest
{
public MyRequest()
{
RowCount = 10;
}
public int Status {get;set;}
public string Current {get;set;}
public int RowCount {get;set;}
}
Changing the nancy to Get["/cars/{status:int}"] = parameters => did the trick of catching the request.
The ajax wasn't being called because I lost the JQuery first line...
$(document).ready(function() {
To get the current and rowCount you need to use
var current = (int)Request.Form["current"];
var rowCount = (int)Request.Form["rowCount];
By the way, the Get wasn't working (I think its a Bootgrid bug) so I changed it to POST.
The simplest way to debug any jQuery library is by using the in-built debugger, it's kinda difficult for me to use chrome for that , so I use Firefox but if you are habitual of chrome then use it, the functionality is almost the same, but with Firefox you can directly switch to the events associated with any element in the html (in the inspect section)
Once you get into the debugger, set the breakpoint and refresh the page either by F5 or Ctrl+F5 if you selected the valid breakpoint you can see all the values associated with every variable also with every function.
Secondly, use the step-in option in the debugger to see where the exact line is pointing, if it's refering to any other file it will pop open automatically in the debugger menu. Firefox's spider monkey is much good at debugging and relating codes (that's totally my opinion).
3- for the api calls, the reason for data not being processed or not displayed, very much lies within the structure of the library,(on what parameters the data is called/fetched/retrieved), for this try to use the "watch expressions" option in debugger and try implementing the code on loaded dom in console section with trigger on the node which you think is bugged or which should display the value.

Firefox extension: share state

I have a Firefox overlay extension with a tree in a sidebar.
How can I keep the tree state synchronized in several windows?
For example in first window added new item in tree, how update tree in other windows?
If somebody can show minimal code for it (with use code modules, observers, broadcasters or something else), please help.
I read similar question, but it did not help:
Firefox extension - Share common state between two or more windows
The answer in the question you reference is good, but short on explanation. You should read the references to which it links. I have duplicated those links here.
One way to keep state information outside of a window context is to use JavaScript code modules (JSM). The section Sharing objects using code modules talks briefly about doing this. Once you have set up your JSM to share the data, it is merely a matter of informing each window that a change has been made and it should update the displayed state. This is easily accomplished by using an event which you define. All of the sidebars listen for a particular event in their window. Then there is one function in the JSM which runs through all the windows signalling them that they need to update.
The code to signal could look something like:
Components.utils.import("resource://gre/modules/Services.jsm");
function forEachOpenWindow(todo) {
// Apply a function to all open browser windows
var windows = Services.wm.getEnumerator("navigator:browser");
while (windows.hasMoreElements()) {
todo(windows.getNext().QueryInterface(Components.interfaces.nsIDOMWindow));
}
}
function signalUpdateNeeded(window){
let event = window.document.createEvent("Event");
event.initEvent("myExtensionName-UpdateAvailable",false,false);
window.dispatchEvent(event);
}
function sendUpdateAvailableToAllWindows(){
forEachOpenWindow(signalUpdateNeeded);
}
Then in the code for the sidebar:
//This imports your JSM, it does not need the .jsm extension, you can use
// whatever extension you want.
Components.utils.import("chrome://MyExtension/content/moduleName.jsm");
window.addEventListener("myExtensionName-UpdateAvailable",
updateDataFromModule, false);
//Instead you may need the following (or another way to get to the
// top window). What is actually needed will depend on the context in
// which your sidebar code is running. You should see below for code to
// access the main browser window from within a sidebar.
//window.top.addEventListener("myExtensionName-UpdateAvailable",
// updateDataFromModule, false);
function updateDataFromModule(){
//Whatever it is you need to do here.
mylocalVariable = myExtensionModule.dataStructure.whatever;
}
Refactoring the first code section above so that it looks like it is in a module that uses one variable to reduce namespace clutter. The code for the module could be something like:
var EXPORTED_SYMBOLS = [ "myExtensionModule" ];
Components.utils.import("resource://gre/modules/Services.jsm");
var myExtensionModule = {
dataStructure: {
whatever: true,
you: 1,
want: ["here.", "It", "is", "your", "data."]
};
forEachOpenWindow: function(todo){
// Apply a function to all open browser windows
var windows = Services.wm.getEnumerator("navigator:browser");
while (windows.hasMoreElements()) {
todo(windows.getNext()
.QueryInterface(Components.interfaces.nsIDOMWindow));
}
},
signalUpdateNeeded: function(window){
let event = window.document.createEvent("Event");
event.initEvent("myExtensionName-UpdateAvailable",false,false);
window.dispatchEvent(event);
},
sendUpdateAvailableToAllWindows: function(){
this.forEachOpenWindow(this.signalUpdateNeeded);
}
}
I have not actually tested this, so there may be some errors.
Having either your sidebar code access the main browser window, or the JSM code find which sidebar your code is in (in order to send or listen fro events) may be a bit more complicated than you think. You should see Working with windows in chrome code. Specifically, Accessing the elements of the top-level document from a child window. That section provides the following code to access the main browser window from within a sidebar:
var mainWindow = window
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
An alternative is for your JSM to keep a reference to an object in the data structure on which all of the sidebars place listeners. This could be an object which it creates. If you do use this method and choose to use a window, then you need to make sure that handle releasing the reference if the window is closed. If you don't you could end up with a memory leak.

Single page application with Rails 4 and AngularJS

Ok, this idea might seem quite a bit crazy and it kindo' is (at least for me at my level).
I have a fairly standarad rails app (some content pages, a blog, a news block, some authentication). And I want to make it into a single page app.
What I want to accomplish is:
All the pages are fetched through AJAX like when using turbolinks, except that the AJAX returns only the view part (the yield part in the layout) withought the layout itself, which stays the same (less data in the responces, quicker render and load time).
The pages are mostly just static html with AngularJS markup so not much to process.
All the actual data is loaded separately through JSON and populated in the view.
Also the url and the page title get changed accordingly.
I've been thinking about this concept for quite a while and I just can't seem to come up with a solution. At this point I've got to some ideas on how this actualy might be done along with some problems I can't pass. Any ideas or solutions are greatly appreciated. Or might be I've just gone crazy and 3 small requests to load a page are worse then I big that needs all the rendering done on server side.
So, here's my idea and known problems.
When user first visits the app, the view template with angular markup is rendered regularly and the second request comes from the Angular Resource.
Then on ngClick on any link that adress is sent to ngInclude of the content wrapper.
How do I bind that onClick on any link and how can I exclude certain links from that bind (e.g. links to external authentication services)?
How do I tell the server not to render the layout if the request is comming from Angular? I though about adding a parameter to the request, but there might be a better idea.
When ngInclude gets the requested template, it fires the ngInit functions of the controllers (usually a single one) in that template and gets the data from the server as JSON (along with the proper page title).
Angular populates the template with the received data, sets the browser url to the url of the link and sets the page title to what it just got.
How do I change the page title and the page url? The title can be changed using jQuery, but is there a way through Angular itself?
Again, I keep thinking about some kind of animation to make this change more fancy.
Profit!
So. What do you guys think?
OK, in case enyone ever finds this idea worth thinking about.
The key can be solved as follows.
Server-side decision of whether to render the view or not.
Use a param in the ngInclude and set the layout: false in the controller if that param is present.
Have not found an easier way.
Client-side binding all links except those that have a particular class no-ajax
Here's a directive that does it.
App.directive('allClicks', function($parse) {
return {
restrict: 'A',
transclude: true,
replace: true,
link: function(scope, element, attrs) {
var $a = element.find('a').not($('a.no-ajax')),
fn = $parse(attrs['allLinks']);
$a.on('click', function(event) {
event.preventDefault();
scope.$apply(function() {
var $this = angular.element(event.target);
fn(scope, {
$event: event,
$href: $this.attr('href'),
$link: $this
});
});
});
}
};
})
And then use it on some wrapper div or body tag like <body ng-controller="WrapperCtrl" all-links="ajaxLink($href)"> and then in your content div do <div id="content" ng-include="current_page_template">
In your angular controller set the current_page template to the document.URL and implement that ajaxLink function.
$scope.ajaxLink = function(path) {
$scope.current_page_template = path+"?nolayout=true";
}
And then when you get your JSON with your data from the server don't forget to use history.pushState to set the url line and document.title = to setr the title.

The view area of ckEditor sometimes shows empty at the start

I am using the following directive to create a ckEditor view. There are other lines to the directive to save the data but these are not included as saving always works for me.
app.directive('ckEditor', [function () {
return {
require: '?ngModel',
link: function ($scope, elm, attr, ngModel) {
var ck = ck = CKEDITOR.replace(elm[0]);
ngModel.$render = function (value) {
ck.setData(ngModel.$modelValue);
setTimeout(function () {
ck.setData(ngModel.$modelValue);
}, 1000);
}; }
};
}])
The window appears but almost always the first time around it is empty. Then after clicking the [SOURCE] button to show the source and clicking it again the window is populated with data.
I'm very sure that the ck.setData works as I tried a ck.getData and then logged the output to the console. However it seems like ck.setData does not make the data visible at the start.
Is there some way to force the view window contents to appear?
You can call render on the model at any time and it will simply do whatever you've told it to do. In your case, calling ngModel.$render() will grab the $modelValue and pass it to ck.setData(). Angular will automatically call $render whenever it needs to during its digest cycle (i.e. whenever it notices that the model has been updated). However, I have noticed that there are times when Angular doesn't update properly, especially in instances where the $modelValue is set prior to the directive being compiled.
So, you can simply call ngModel.$render() when your modal object is set. The only problem with that is you have to have access to the ngModel object to do that, which you don't have in your controller. My suggestion would be to do the following:
In your controller:
$scope.editRow = function (row, entityType) {
$scope.modal.data = row;
$scope.modal.visible = true;
...
...
// trigger event after $scope.modal is set
$scope.$emit('modalObjectSet', $scope.modal); //passing $scope.modal is optional
}
In your directive:
ngModel.$render = function (value) {
ck.setData(ngModel.$modelValue);
};
scope.$on('modalObjectSet', function(e, modalData){
// force a call to render
ngModel.$render();
});
Its not a particularly clean solution, but it should allow you to call $render whenever you need to. I hope that helps.
UPDATE: (after your update)
I wasn't aware that your controllers were nested. This can get really icky in Angular, but I'll try to provide a few possible solutions (given that I'm not able to see all your code and project layout). Scope events (as noted here) are specific to the nesting of the scope and only emit events to child scopes. Because of that, I would suggest trying one of the three following solutions (listed in order of my personal preference):
1) Reorganize your code to have a cleaner layout (less nesting of controllers) so that your scopes are direct decendants (rather than sibling controllers).
2) I'm going to assume that 1) wasn't possible. Next I would try to use the $scope.$broadcast() function. The specs for that are listed here as well. The difference between $emit and $broadcast is that $emit only sends event to child $scopes, while $broadcast will send events to both parent and child scopes.
3) Forget using $scope events in angular and just use generic javascript events (using a framework such as jQuery or even just roll your own as in the example here)
There's a fairly simple answer to the question. I checked the DOM and found out the data was getting loaded in fact all of the time. However it was not displaying in the Chrome browser. So the problem is more of a display issue with ckEditor. Strange solution seems to be to do a resize of the ckEditor window which then makes the text visible.
This is a strange issue with ckeditor when your ckeditor is hidden by default. Trying to show the editor has a 30% chance of the editor being uneditable and the editor data is cleared. If you are trying to hide/show your editor, use a css trick like position:absolute;left-9999px; to hide the editor and just return it back by css. This way, the ckeditor is not being removed in the DOM but is just positioned elsewhere.
Use this java script code that is very simple and effective.Note editor1 is my textarea id
<script>
$(function () {
CKEDITOR.timestamp= new Date();
CKEDITOR.replace('editor1');
});
</script>
Second way In controller ,when your query is fetch data from database then use th
is code after .success(function().
$http.get(url).success(function(){
CKEDITOR.replace('editor1');
});
I know, that this thread is dead for a year, but I got the same problem and I found another (still ugly) solution to this problem:
instance.setData(html, function(){
instance.setData(html);
});

Resources