NativeScript – Useful Resources ”; Previous Next The following resources contain additional information on NativeScript. Please use them to get more in-depth knowledge on this. Useful Links on NativeScript NativeScript @ NativeScript − NativeScript, its history and various other terms has been explained in simple language. NativeScript Wiki − Wikipedia Reference for NativeScript. Useful Books on NativeScript To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;
Category: nativescript
NativeScript – Data Binding
NativeScript – Data Binding ”; Previous Next Data binding is one of the advanced concepts supported by NativeScript. NativeScript follows Angular data binding concept as closely as possible. Data binding enables the UI component to show/update the current value of the application data model without any programming effort. NativeScript supports two type of data binding. They are as follows − One-Way data binding − Update the UI whenever the model is changed. Two-Way data binding − Sync the UI and model. Whenever the model is updated, UI is updated automatically and also whenever the UI gets data from user (UI gets updated), the model will be updated. Let us learn both the concepts in this section. One-Way Data Binding NativeScript provides a simple option to enable one-way data binding in a UI component. To enable one-way data binding, just add square bracket in the property of the target UI and then assign it the necessary model’s property. For example, to update the text content of a Label component, just change the UI code as below − <Label [text]=”this.model.prop” /> Here, this.model.prop refers to the property of the model, this.model. Let us change our BlankNgApp to understand the one-way data binding. Step 1 Add a new model, User (src/model/user.ts) as follows − export class User { name: string } Step 2 Open UI of our component, src/app/home/home.component.html and update the code as below − <ActionBar> <Label text=”Home”></Label> </ActionBar> <GridLayout columns=”*” rows=”auto, auto, auto”> <Button text=”Click here to greet” class=”-primary” color=”gray” (tap)=”onButtonTap($event)” row=”1” column=”0”> </Button> <Label [text]=”this.user.name” row=”2” column=”0” height=”50px” textAlignment=”center” style=”font-size: 16px; font-weight: bold; margin: 0px 32px 0 25px;”> </Label> </GridLayout> Here, Label’s text is set to the user model’s property name. Button tap event is attached to onButtonTap method. Step 3 Open code of the home component, src/app/home/home.component.ts and update the code as below − import { Component, OnInit } from “@angular/core”; import { User } from “../../model/user” @Component({ selector: “Home”, templateUrl: “./home.component.html” }) export class HomeComponent implements OnInit { public user: User; constructor() { // Use the component constructor to inject providers. this.user = new User(); this.user.name = “User1″; } ngOnInit(): void { // Init your component properties here. } onButtonTap(args: EventData) { this.user.name = ”User2”; } } Here, user model is imported User object is created in component’s constructor onButtonTap event is implemented. Implementation of onButtonTap updates the User object and set name of the property as User2 Step 4 Compile and run the application and click the button to change the model and it will automatically change the Label text. The initial and final state of the application is as follows − Initial State One Way Data Binding Initial State is shown below − Final State One Way Data Binding Final State is shown below − Two-way Data Binding NativeScript also provides two-way data binding for advanced functionality. It binds the model data to UI and also binds the data updated in UI to model. To do two-way data binding, use ngModel property and then surround it with [] and () as below − <TextField [(ngModel)] = ”this.user.name”></TextField> Let us change the BlankNgApp application to better understand the two-way data binding. Step 1 Import NativeScriptFormsModule into the HomeModule (src/app/home/home.module.ts) as specified below − import { NgModule, NO_ERRORS_SCHEMA } from “@angular/core”; import { NativeScriptCommonModule } from “nativescript-angular/common”; import { HomeRoutingModule } from “./home-routing.module”; import { HomeComponent } from “./home.component”; import { NativeScriptFormsModule } from “nativescript-angular/forms”; @NgModule({ imports: [ NativeScriptCommonModule, HomeRoutingModule, NativeScriptFormsModule ], declarations: [ HomeComponent ], schemas: [ NO_ERRORS_SCHEMA ] }) export class HomeModule { } Here, NativeScriptFormsModule enables the two-way data binding. Otherwise, the two-way data binding will not work as expected. Step 2 Change the UI of the home component as given below − <ActionBar> <Label text=”Home”></Label></ActionBar> <GridLayout columns=”*” rows=”auto, auto”> <TextField hint=”Username” row=”0” column=”0” color=”gray” backgroundColor=”lightyellow” height=”75px” [(ngModel)]=”this.user.name”> </TextField> <Label [text]=”this.user.name” row=”1” column=”0” height=”50px” textAlignment=”center” style=”font-size: 16px; font-weight: bold; margin: 0px 32px 0 25px;”> </Label> </GridLayout> Here, Label component’s text property is set with one-way data binding. If the model user is updated, then its text property will automatically get updated. TextField component sets the ngModel as this.user.name. If the model user is updated, then it’s text property will automatically get updated. At the same time, if user changes the TextField’s value, then the model gets updated as well. If the model gets updated, it will trigger Label’s text property changes as well. So, if user changes data, then it will show in Label’s text property. Step 3 Run the application and try to change the value of text box. The initial and final state of the application will be similar as specified below − Initial State Two-way data binding – Initial state is given below − Final State Two-way data binding – Final state is shown below − Print Page Previous Next Advertisements ”;
NativeScript – Navigation
NativeScript – Navigation ”; Previous Next Navigation enables users to quickly swipe in to their desired screen or to navigate through an app or to perform a particular action. Navigation component helps you implement navigation using simple button clicks to more complex patterns. Navigation differ substantially between core and angular version of NativeScript. While core framework navigation is foundation for navigation process, NativeScript’s Angular model adopts the core navigation concept and extends it to make it compatible with Angular framework. Let us see both core navigation concept and angular adoption of navigation in this chapter. Core Concepts Let us understand how the navigation works in core NativeScript in this chapter. In NativeScript, navigation is split into four different categories based on the direction it applies as specified below − Forward navigation Backward navigation Lateral navigation Bottom navigation Forward Navigation Forward Navigation refers to navigating users to the screen in the next level of hierarchy. It is based on two NativeScript components, Frame and Page. Frame Frame is the root level component for navigation. It is not a visible container but acts as a container for transitions between pages. A simple example is as follows − <Frame id=”featured” defaultPage=”featured-page” /> Here, Frame navigates to (or loads) the featured-page page component and renders it. Page Page is next to Frame component and it acts as a container for UI component. Simple example is defined below − <Page loaded=”onPageLoaded”> <ActionBar title=”Item” class=”action-bar”></ActionBar> <AbsoluteLayout> <Label text=”Label”/< <Button text=”navigate(”another-page”)” tap=”onTap”/> </AbsoluteLayout> </Page> Here, Initially, Page loads all the UI component of the screen and renders it. When user clicks the button, it will navigate the user to another-page page. Backward Navigation Backward navigation method enables backward movement through screens within one app or across different apps. It is the opposite direction of forward navigation. Simple goBack() method is used to navigate back to the previous page. It is defined below − <Page class=”page” loaded=”onPageLoaded”> <ActionBar title=”Item” class=”action-bar”></ActionBar> <StackLayout class=”home-panel”> <Button class=”btn btn-primary” text=”Back” tap=”goBack”/> </StackLayout> </Page> Here, goBack() method will be triggered when user taps the button. goBack() navigates the users to the previous page, if one is available. Lateral Navigation Lateral navigation refers to the navigation between screens at same levels of hierarchy. It is based on hub pattern. It is enabled through specific navigation components such as BottomNavigation, Tabs, TabView, SideDrawer and Modal View. A simple example is defined as below − <Page class=”page” xmlns=”http://www.nativescript.org/tns.xsd”> <ActionBar title=”Hub” class=”action-bar”></ActionBar> <StackLayout class=”home-panel”> <Button class=”btn btn-primary” text=”navigate(”featured-page”)” tap=”navigateToFeatured” /> <Button class=”btn btn-primary” text=”navigate(”search-page”)” tap=”navigateToSearch” /> </StackLayout> </Page> Here, navigateToFeatured function uses navigate() method to navigate the user to featured page. Similarly, navigateToSearch function will navigate the user to search page. The hub page can also be reached using navigate method available in page screen and one can move out of hub page using goBack() method. A simple example is as follows − <Page class=”page”> <ActionBar title=”Item” class=”action-bar”></ActionBar> <StackLayout class=”home-panel”> <Button class=”btn btn-primary” text=”navigate(”hub-page”)” tap=”navigateToHub” /> <Button class=”btn btn-primary” text=”goBack()” tap=”goBack” /> </StackLayout> </Page> Bottom and Tab Navigation The most common style of navigation in mobile apps is tab-based navigation. The Tab Navigation is arranged at the bottom of the screen or on the top below the header. It is achieved by using TabView and BottomNavigation component. Angular based navigation NativeScript extends its navigation concept to accommodate the Angular routing concept. NativeScript provides a new module, NativeScriptRouterModule by extending Angular RouterModule. NativeScript angular navigation concept can be categorized into section as below − page-router-outlet tag nsRouterLink attractive RouterExtension class Custom RouterReuseStrategy Let us learn all the above angular navigation in this section. Page Router Outlet As learned earlier, page-router-outlet is the replacement of Angular’s router-outlet. page-router-outlet wraps the Frame and Page strategy of Nativescript core navigation framework. Each page-router-outlet creates a new Frame component and each configured components in the outlet will be wrapped using Page component. Then, the native navigate method is used to navigate to another page / route. Router Link (nsRouterLink) nsRouterLink is the replacement of Angular’s RouterLink. It enables UI component to link to another page using route. nsRouterLink also provides below two options − pageTransition − It is used to set page transition animation. true enables default transition. false disables the transition. Specific values like slide, fadein, etc., set the particular transition. clearHistory − true clears the navigation history of nsRouterLink. A simple example code is as follows − <Button text=”Go to Home” [nsRouterLink]=”[”/home”]” pageTransition=”slide” clearHistory=”true”></Button> Router Extension NativeScript provides RouterExtensions class and exposes the navigation function of the core NativeScript. The methods exposed by RouterExtensions are as follows − navigate navigateByUrl back canGoBack backToPreviousPage canGoBackToPreviousPage A simple example code using RouterExtensions is as follows − import { RouterExtensions } from “nativescript-angular/router”; @Component({ // … }) export class HomeComponent { constructor(private routerExtensions: RouterExtensions) { } } Custom Route Reuse Strategy NativeScript uses a custom route reuse strategy (RouterReuseStrategy) to accommodate the architecture of a mobile application. A mobile application differs in certain aspects in comparison to a web application. For example, the page can be destroyed in a web application when user navigates away from the page and recreates it when the user navigates to the page. But, in mobile application, the page will be preserved and reused. These concepts are taken into consideration while designing the routing concept.
NativeScript – Introduction
NativeScript – Introduction ”; Previous Next Generally, developing a mobile application is a complex and challenging task. There are many frameworks available to develop a mobile application. Android provides a native framework based on Java language and iOS provides a native framework based on Objective-C/Shift language. However, to develop an application that support both operating systems, we need to code in two different languages using two different frameworks. To overcome this complexity, mobile frameworks supports this feature. The main reason behind to use cross-platform or hybrid framework is easier to maintain a single code base. Some of the popular frameworks are NativeScript, Apache Cordova, Xamarin, etc. Overview of JavaScript Frameworks JavaScript is a multi-paradigm language. It supports functional programming, object-oriented and prototype based programming. JavaScript was initially used for the client-side. Nowadays, JavaScript is used as a server-side programming language as well. JavaScript frameworks are a type of tool that makes working with JavaScript easier and smoother. Using this framework, programmers can easily code the application as a device responsive. Responsiveness is one of the reasons behind why this framework is becoming very popular. Let us have a look at some of the popular JS frameworks − Angular One of the most powerful, efficient, and open-source JavaScript frameworks is Angular. We can build mobile and desktop applications. Google uses this framework. It is used for developing a Single Page Application (SPA). Vue.js VueJS is a progressive JavaScript framework used to develop interactive web interfaces. It is one of the famous frameworks used to simplify web development. It can be easily integrated into big projects for front-end development without any issues. It is dual integration mode is one of the most attractive features for the creation of high-end SPA or Single Page Application. React ReactJS is JavaScript library used for building reusable UI components. It is developed by Facebook. It is currently one of the most popular JavaScript libraries and has a strong foundation and large community behind it. Node.js Node.js is an open source, cross-platform runtime environment for developing server-side and networking applications. It is built on Google Chrome’s JavaScript Engine (V8 Engine). Node.js applications are written in JavaScript, and can be run on OS X, Microsoft Windows,and Linux. It provides a rich library of various JavaScript modules which simplifies the development of web applications. Overview of NativeScript NativeScript is an open source framework used for creating native iOS and android mobile applications. It is a JIT compiled framework. NativeScript code runs on JS virtual machine. It uses V8 engine runtime for both Android and iOS platforms. NativeScript uses XML, JS and CSS for development. It has a WebIDE known as PlayGround. This PlayGround supports easy working interface, easy to manage projects, hot reload and debug on devices. NativeScript allows developers to create native, cross-platform apps quickly and efficiently and save on the costs of development, testing, and training. Hence, Native apps will continue to be rich and strong for years to come to make better and easier to use. Features NativeScript has vibrant community support. Some of the salient features of NativeScript listed below − Extensible Hot Module Replacement Easy to setup We can build rich animations, graphs, charts and lists Developers can use any view as the root of an application Lazy coding Benefits NativeScript helps small or large scale companies to build cross-platform mobile apps. Some of the key benefits are − Developers can reuse existing tools and code Easy to modify, troubleshoot and update newer versions Development experience is good so we don’t have to spend time to learn new tools Platform-specific APIs from JavaScript, eliminating the need to learn Cordova plugins Ease authentication with different sign-on providers Print Page Previous Next Advertisements ”;
NativeScript – Plugins
NativeScript – Plugins ”; Previous Next The npm package is used for adding native functionality. Using this package, we can install or search or delete any plugins. This section explains about plugins in detail. Commands add − It is used to install plugin. update − Updates specified plugin and modify its dependencies. remove − Removes the plugin. build − It is used to build plugin for iOS or android projects. create − Creates a plugin for your project. Adding Plugin Below syntax is used to add a new plugin − tns plugin add <plugin-name> For example, if you want to add nativescript-barcodescanner, you can use the following code − tns plugin add nativescript-barcodescanner You could see the following response − + [email protected] added 1 package from 1 contributor and audited 11704 packages in 8.76s You can also use npm module to add the above plugin − npm install nativescript-barcodescanner Now, NativeScript CLI downloads the plugin from npm and add inside your node_modules folder. If you want to add the plugin directly to your package.json and resolve all the dependency issues, you can use the below command instead of the previous one − npm i nativescript-barcodescanner If you want to install a developer dependencies during development, use the below code − npm i tns-platform-declarations –save-dev Here, tns-platform-declarations is a developer dependency required only for intelliSense during the development process. Importing Plugins Now, we have installed nativescript-barcodescanner plugin. Let us add inside your project using the below command − const maps = require(“nativescript-barcodescanner”); maps.requestPermissions(); Updating Plugins This method is used to update a specified plugin so it uninstalls previous one and installs new version and modify its dependencies. It is defined below − tns plugin update <Plugin name version> Removing Plugin If you want remove the plugin, if not required, you can use the below syntax − tns plugin remove <plugin-name> For example, if you want to remove the above installed nativescript-google-maps-sdk, then use the below command − tns plugin remove nativescript-barcodescanner You could see the following response − Successfully removed plugin nativescript-barcodescanner Building Plugins It is used to build the plugin’s Android-specific project files located in platforms/android. Let us build the nativescript-barcodescanner pugin using the below command − tns plugin build nativescript-barcodescanner Creating Plugins NativeScript plugins are simple JavaScript modules. It is defined inside your application srcpackage.json file. This module is used to create a new project for NativeScript plugin development. It is defined below − tns plugin create <Plugin Repository Name> [–path <Directory>] Print Page Previous Next Advertisements ”;
NativeScript – Native APIs Using JavaScript ”; Previous Next This section explains about the overview of accessing Native APIs using JavaScript. Marshalling The NativeScript Runtime provides implicit type conversion for both android and iOS platforms. This concept is known as marshalling. For example, NativeScript- iOS paltform can implicitly convert JavaScript and Objective-C data types similarly, Java/Kotlin can easily be mapped to JavaScript project types and values. Let us understand how to perform marshalling in each type one by one briefly. Numeric Values We can easily convert iOS and android numeric data types into JavaScript numbers. Simple numeric conversion for iOS into JavaScript is defined below − console.log(`max(7,9) = ${max(7,9)}`); Here, The native max() function is converted into JavaScript number. Android Environment Java supports different numeric types such as byte, short, int, float, double and long. JavaScript has only number type. Consider a simple Java class shown below − class Demo extends java.lang.Object { public int maxMethod(int a,int b) { if(a>b) { return a; } else { return b; } } } Here, The above code contains two integer arguments. We can call the above code object using JavaScript as shown below − //Create an instance for Demo class var obj = new Demo(); //implicit integer conversion for calling the above method obj.maxMethod(7,9); Strings Android strings are defined in java.lang.string and iOS strings are defined in NSSring. Let us see how to perform marshalling in both platforms. Android Strings are immutable but String buffers support mutable strings. Below code is an example for simple mapping − //Create android label widget var label = new android.widget.Label(); //Create JavaScript string var str = “Label1″; //Convert JavaScript string into java label.setText(str); // text is converted to java.lang.String Boolean class is defined in java.lang.Boolean. This class wraps a value of boolean in an object. We can easily convert boolean to String and vice-versa. Simple example is defined as given below − //create java string let data = new java.lang.String(”NativeScript”); //map java String to JavaScript string, let result = data.startsWith(”N”); //return result console.log(result);// true iOS environment NSString class is immutable but its subclass NSMutableString is immutable. This class contains a collection of methods for working with strings. It is declared as below − class NSString : NSObject Consider a simple objective-c declaration as shown below − NSString *str = @”nativescript”; //convert the string to uppercase NSString *str1; str1 = [str uppercaseString]; NSLog(@”Uppercase String : %@n”, str1 ); NSStrings can easily be mapped to JavaScript strings. Array This section explains about how to perform marshalling in arrays. Let’s take an example of iOS environment first. Array Declaration class NSArray : NSObject Here, NSArray is used to manage ordered collection of objects called arrays. It is used to create static array. Its sub class NSMutableArray is used to create dynamic arrays. Consider NSArray objects can be created using array literals as shown below − let array: NSArray = [“React”,”Vue”,”TypeScript”] Now, we can map this array into JavaScript as shown below − //create native array let nsArr = NSArray.arrayWithArray(“React”,”Vue”,”TypeScript”]); //create simple javascript array let jsArr = [“Hello,World”,”NativeScript”]; //Now compare the two arrays, let compare = nsArr.isEqual(jsArr); console.log(comapre); This will return the output as false. Android array declaration Java arrays are defined in java.util.Arrays. This class contains various methods for manipulating arrays. An example is shown below − //javascript array let data = [12,45,23,56,34,78,50]; //create java array let result = ns.example.Math.maxElement(data); console.log(result); Classes and Objects Classes and Objects are basic concepts of Object Oriented Programming. Class is a user defined prototype. Object is an instance of class. Class represents the set of properties or methods that are common to all objects of one type. Let us understand native classes and objects for both mobile development environments. Android Environment Java and Kotlin classes have unique identifiers denoted by the full package name. For example, android.view.View − It is a basic user interface class for screen layout and interaction with the user. We can access this class in JavaScript as shown below − const View = android.view.View; First, we import the class using the below statement − import android.view.View; Next create a class as given below − public class MyClass { public static void staticMethod(context) { //create view instance android.view.View myview = new android.view.View(context); } } In the above same class, we can access JavaScript function using the below code − const myview = new android.view.View(context); Similarly, we can access interfaces, constants and enumerations within java.lang packages. iOS Environment Objective-C classes are defined in two sections @interface and @implementation. Class definition starts with the keyword @interface followed by the interface(class) name. In Objective-C, all classes are derived from the base class called NSObject. It is the superclass of all Objective-C classes. Simple Circle class is defined as shown below − @interface Circle:NSObject { //Instance variable int radius; } @end Consider a class with one method as shown below − @interface MyClass : NSObject + (void)baseStaticMethod; @end This class can be converted to javascript using the below code − function MyClass() { /* native call */ }; Object.setPrototypeOf(MyClass, NSObject); BaseClass.baseStaticMethod = function () { /* native call */ }; JavaScript instanceof operator is used to verify, if an object inherits from a given class. This can be defined as − var obj = MyClass.alloc().init(); //
NativeScript – Testing
NativeScript – Testing ”; Previous Next Testing is a very important phase in the development life cycle of an application. It ensures an application quality. It needs careful planning and execution. It is also most time consuming phase of the development. NativeScript framework provides an extensive support for the automated testing of an application. Types of Testing Generally, three types of testing processes are available to test an application. They are as follows − Unit Testing Unit testing is the easiest method to test an application. It is based on ensuring the correctness of a piece of code (a function, in general) or a method of a class. But, it does not reflect the real environment and subsequently. It is the least option to find the bugs. Generally, NativeScript uses Jasmine, Mocha with Chai and QUnit unit testing frameworks. To perform this, first you need to configure in your project using the below command − tns test init Now, you get the following response − ? Select testing framework: (Use arrow keys) > jasmine mocha qunit Now, select jasmine framework and your screen looks similar to this − ? Select testing framework: jasmine + [email protected] added 90 packages from 432 contributors and audited 11944 packages in 8.753s + [email protected] added 2 packages from 1 contributor and audited 11946 packages in 7.299s > [email protected] postinstall /Users/workspace/NativeScript/NativeApp/node_modules/core-js > node -e “try{require(”./postinstall”)}catch(e){}” Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library! The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: > https://opencollective.com/core-js > https://www.patreon.com/zloirock Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -) npm WARN [email protected] requires a peer of webpack@^2.0.0 || ^3.0.0 but none is installed. You must install peer dependencies yourself. + [email protected] added 19 packages from 52 contributors and audited 12012 packages in 9.368s + [email protected] added 2 packages from 35 contributors and audited 12014 packages in 6.925s + [email protected] updated 1 package and audited 12014 packages in 7.328s + @types/[email protected] > [email protected] postinstall /Users/deiva/workspace/NativeScript/NativeApp/node_modules/nativescript-unit -test-runner > node postinstall.js + [email protected] added 1 package from 1 contributor and audited 12032 packages in 7.14s Successfully installed plugin nativescript-unit-test-runner. Example test file created in src/tests Run your tests using the “$ tns test <platform>” command. Now, the test file is created inside srctestsexample.ts. Create Your Tests Let us add a simple test inside example.ts file as shown below − describe(“NativeApp test:”, function() { it(“Check counter.”, function() { expect(mainViewModel.createViewModel().counter).toEqual(10); }); it(“Check message.”, function () { expect(mainViewModel.createViewModel().message).toBe(“10 taps left”); }); }); Here, First, check if the counter equals 10 and check if the message is 10 taps left. Let us run the test in next step. Run Your Tests Now, run the test in either android or iOS connected device using the below command − tns test android This will return the following status − ? To continue, choose one of the following options: (Use arrow keys) > Configure for Cloud Builds Configure for Local Builds Configure for Both Local and Cloud Builds Skip Step and Configure Manually Then choose the below option − ? To continue, choose one of the following options: Configure for Local Builds Running the setup script to try and automatically configure your environment. These scripts require sudo permissions ….. To execute your test suite in the android simulator, run the following command − tns test android –emulator Now, karma server prepares builds and deploy your project. End To End (E2E) Testing Unit tests are small, simple and fast process whereas, E2E testing phase multiple components are involved and works together which cover flows in the application. This could not be achieved by unit and integration tests. NativeScript Appium plugin is used to perform E2E automation testing. Well, Appium is an open source testing framework for mobile app. To add this framework in your project, you must have either latest version of XCode or Android SDK above 25.3.0. Install Appium Let us install Appium globally using npm module − npm install -g appium Now, you could see the following response − npm install -g appium /Users/.npm-global/bin/authorize-ios -> /Users/.npm-global/lib/node_modules/ appium/node_modules/.bin/authorize-ios > [email protected] install /Users/.npm-global/lib/node_modules/ appium/node_modules/appium-windows-driver > node install-npm.js Not installing WinAppDriver since did not detect a Windows system > [email protected] postinstall /Users/.npm- global/lib/node_modules/appium/node_modules/core-js > node -e “try{require(”./postinstall”)}catch(e){}” Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library! The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: > https://opencollective.com/core-js > https://www.patreon.com/zloirock Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -) > [email protected] postinstall/Users/.npm- global/lib/node_modules/appium/node_modules /appium-chromedriver > node install-npm.js …………………………………….. ……………………………………… + [email protected] added 671 packages from 487 contributors in 28.889s Add Plugin Let us add nativescript-dev-appium plugin as a devDependency to your project using the below command − $ npm install -D nativescript-dev-appium After executing this, choose mocha framework and you will get a response similar to this − > node ./postinstall.js ? What kind of project do you use ? javascript ? Which testing framework do you prefer? mocha + [email protected] Now, files are stored inside your project folder.
NativeScript – Widgets
NativeScript – Widgets ”; Previous Next NativeScript provides a large set of user interface components and are called as ‘widgets’. Each widget does a special task and comes with a set of methods. Let’s understand NativeScript widgets in detail in this section. Button Button is a component to execute tap event action. When a user taps the button it performs the corresponding actions. It is defined below − <Button text=”Click here!” tap=”onTap”></Button> Let us add the button in our BlankNgApp as below − Step 1 Open the srcapphomehome.component.html. This is the UI design page of our home component. Step 2 Add a button inside the GirdLayout component. The complete code is as follows − <ActionBar> <Label text=”Home”></Label> </ActionBar> <GridLayout> <button text=”Click Here!”></button> </GridLayout> Output Below is the output of the button − Step 3 We can style the button using CSS as specified below − <ActionBar> <Label text=”Home”></Label> </ActionBar> <GridLayout> <button text=”Click Here!” class=”-primary”></button> </GridLayout> Here, −primary class is used to represent the primary button. Output Below is the output of ButtonPrimary − Step 4 NativeScript provides formatted option to provide custom icons in the button. The sample code is as follows − <GridLayout> <Button class=”-primary”> <FormattedString> <Span text=”” class=”fa”></Span> <Span text=” Button.-primary with icon”></Span> </FormattedString> </Button> </GridLayout> .fa { font-family: “FontAwesome”, “fontawesome-webfont”; } Here,  specifies the location of the icon in the font, FontAwesome. Download the latest Font Awesome font and place the fontawesome-webfont.ttf in srcfonts folder. Output Below is the output of ButtonPrimary − Step 5 Rounded button can be created using the below syntax − <Button text=”Button.-primary.-rounded-sm” class=”-primary -rounded-sm”></Button> Output Below is the output of ButtonPrimary − Label Label component is used to display static text. Change the home page as below − <GridLayout> <Label text=”NativeScript is an open source framework for creating native iOS and Android apps in TypeScript or JavaScript.” textWrap=”true”> </Label> </GridLayout> Here, textWrap wraps the content of the label, if the label extends beyond the screen width. Output Below is the output of Label − TextField TextField component is used to get information from user. Let us change our home page as specified below − <GridLayout> <TextField hint=”Username” color=”lightblue” backgroundColor=”lightyellow” height=”75px”> </TextField> </GridLayout> Here, color represent text color backgroundColor represent background of the text box height represent the height of the text box Output Below is the output of Text Field − TextView TextView Component is used to get multi-line text content from the user. Let us change our home page as specified below − <GridLayout> <TextView loaded=”onTextViewLoaded” hint=”Enter text” returnKeyType=”done” autocorrect=”false” maxLength=”100″> </TextView> </GridLayout> Here, maxLength represent maximum length accepted by TextView. Output Below is the output of TextView − SearchBar This component is used for search any queries or submit any request. It is defined below − <StackLayout> <SearchBar id=”bar” hint=”click here to search …”></SearchBar> <StackLayout> We can apply styles − <StackLayout> <SearchBar id=”bar” hint=”click here to search …” color=”green” backgroundColor=”green”></SearchBar> </StackLayout> Below is the output of SearchBarStyle − Switch Switch is based on toggle to choose between options. Default state is false. It is defined below − <StackLayout> <Switch checked=”false” loaded=”onSwitchLoaded”></Switch> </StackLayout> The output for the above program is shown below − Slider Slider is a sliding component to pick a numeric range. It is defined below − <Slider value=”30″ minValue=”0″ maxValue=”50″ loaded=”onSliderLoaded”></Slider> The output for the above program is given below − Progress Progress widget indicates progress in an operation. Current progress is represented as bar. It is defined below − <StackLayout verticalAlign=”center” height=”50″> <Progress value=”90″ maxValue=”100″ backgroundColor=”red” color=”green” row=”0″></Progress> </StackLayout> Below is the output of Progress widget − ActivityIndicator ActivityIndicator shows a task in a progress. It is defined below − <StackLayout verticalAlign=”center” height=”50″> <ActivityIndicator busy=”true” color=”red” width=”50″ height=”50″></ActivityIndicator> </StackLayout> Below is the output for ActivityIndicator − Image Image widget is used to display an image. It can be loaded using ‘ImageSource’ url. It is defined below − <StackLayout class=”m-15″ backgroundColor=”lightgray”> <Image src=”~/images/logo.png” stretch=”aspectFill”></Image> </StackLayout> The output for Image Widget is as shown below − WebView WebView shows web pages. Web pages can be loaded using URL. It is defined below − <WebView row=”1″ loaded=”onWebViewLoaded” id=”myWebView” src=”http://www.google.com”></WebView> The output for the above code is as shown below − DatePicker DatePicker component is used to pick date. It is defined below − <StackLayout class=”m-15″ backgroundColor=”lightgray”> <DatePicker year=”1980″ month=”4″ day=”20″ verticalAlignment=”center”></DatePicker> </StackLayout> The output of DatePicker component is as shown below − TimePicker TimePicker component is used to pick the time. It is defined below − <StackLayout class=”m-15″ backgroundColor=”lightgray”> <TimePicker hour=”9″ minute=”25″ maxHour=”23″ maxMinute=”59″ minuteInterval=”5″> </TimePicker> </StackLayout> Below is the output of TimePicker component − Print Page Previous Next Advertisements ”;
NativeScript – Modules
NativeScript – Modules ”; Previous Next A NativeScript Module contains a set of related functionalities packaged as single library. Let us learn the modules provided by NativeScript framework. It contains core functionalities of the NativeScript framework. Let us understand the core modules in this chapter. Application Application contains platform specific implementation of mobile application. Simple core module is defined below − const applicationModule = require(“tns-core-modules/application”); Console Console module is used to log message. It has the following methods − console.log(“My FirstApp project”); console.info(“Native apps!”); console.warn(“Warning message!”); console.error(“Exception occurred”); application-settings application-settings module contains method to manage application settings. To add this module, we need to add the following code − const appSettings = require(“tns-core-modules/application-settings”); Few methods available in the application-setting are as follows − setBoolean(key: string, value: boolean) – set boolean object setNumber(key: string, value: number) – set number object setString(key: string, value: string) – sets string object getAllKeys() – Contains all stored keys hasKey(key: string) – check whether a key present or not clear – clears stored values remove – remove any entry based on key. A simple example using application setting is as follows − function onNavigatingTo(args) { appSettings.setBoolean(“isTurnedOff”, false); appSettings.setString(“name”, “nativescript”); appSettings.setNumber(“locationX”, 54.321); const isTurnedOn = appSettings.getBoolean(“isTurnedOn”); const username = appSettings.getString(“username”); const locationX = appSettings.getNumber(“locationX”); // Will return “not present” if there is no value for “noKey” const someKey = appSettings.getString(“noKey”, “not present”); } exports.onNavigatingTo = onNavigatingTo; function onClear() { // Removing a single entry via its key name appSettings.remove(“isTurnedOff”); // Clearing the whole settings appSettings.clear(); } http This module is used for handling http request and response. To add this module in your application, add the following code − const httpModule = require(“tns-core-modules/http”); We can send data using the following methods − getString − It is used to make request and downloads the data from URL as string. It is defined below − httpModule.getString(“https://…/get”).then( (r) => { viewModel.set(“getStringResult”, r); }, (e) => { } ); getJSON − It is used to access data from JSON. It is defined below − httpModule.getJSON(“https://…/get”).then((r) => { }, (e) => { }); getImage − downloads the content from specified URL and return ImageSource object. It is defined below − httpModule.getImage(“https://…/image/jpeg”).then((r) => { }, (e) => { }); getFile − It has two arguments URL and file path. URL − downloads the data. File path − save URL data into the file. It is defined below − httpModule.getFile(“https://”).then((resultFile) => { }, (e) => { }); request − It has options argument. It is used to request options and return HttpResponse object. It is defined below − httpModule.request({ url: “https://…/get”, method: “GET” }).then((response) => { }, (e) => { }); Image-source image-source module is used save image. We can add this module using the below statement − const imageSourceModule = require(“tns-core-modules/image-source”); If you want to load images from resource, use the below code − const imgFromResources = imageSourceModule.fromResource(“icon”); To add image from local file, use the below command − const folder = fileSystemModule.knownFolders.currentApp(); const path = fileSystemModule.path.join(folder.path, “images/sample.png”); const imageFromLocalFile = imageSourceModule.fromFile(path); To save image to the file path, use the below command − const img = imageSourceModule.fromFile(imagePath); const folderDest = fileSystemModule.knownFolders.documents(); const pathDest = fileSystemModule.path.join(folderDest.path, “sample.png”); const saved = img.saveToFile(pathDest, “png”); if (saved) { console.log(” sample image saved successfully!”); } Timer This module is used to execute code at specific time intervals. To add this, we need to use require − const timerModule = require(“tns-core-modules/timer”); It is based on two methods − setTimeout − It is used to delay the execution. It is represented as milliseconds. setInterval − It is used to apply recurring at specific intervals. Trace This module is useful for debugging. It gives the logging information. This module can be represented as − const traceModule = require(“tns-core-modules/trace”); If you want to enable in your application then use the below command − traceModule.enable(); ui/image-cache image-cache module is used to handle image download requests and caches downloaded images. This module can be represented as shown below − const Cache = require(“tns-core-modules/ui/image-cache”).Cache; connectivity This module is used to receive the connection information of the connected network. It can be represented as − const connectivityModule = require(“tns-core-modules/connectivity”); Functionality Modules Functionality modules include lot of system/platform specific modules. Some of the important modules are as follows − platform − Used to display the information about your device. It can be defined as given below − const platformModule = require(“tns-core-modules/platform”); fps-meter − Used to capture frames per second. It can be defined as given below − const fpsMeter = require(“tns-core-modules/fps-meter”); file-system − Used to work with your device file system. It is defined below − const fileSystemModule = require(“tns-core-modules/file-system”); ui/gestures − Used to work with UI gestures. UI module UI module includes the UI component and its related functionality. Some of the important UI modules are as follows − frame page color text/formatted-string xml styling animation Print Page Previous Next Advertisements ”;
NativeScript – Events Handling ”; Previous Next In every GUI application, events play a very important role of enabling user interaction. Whenever user interact with the application, an event fires and a corresponding action will be executed. For example, when user clicks the Login button in the login page of an application, it triggers the login process. Events involve two actors − Event sender − object, which raise the actual event. Event listener − function, which listen for a particular event and then executed when an event is fired. Observable Class It is a pre-defined class to handle events. It is defined below − const Observable = require(“tns-core-modules/data/observable”).Observable; In NativeScript, almost every object derives from Observable class and so every object support events. Event Listener Let us understand how to create an object and add an event listener to the object in this chapter. Step 1 Create a button that is used to generate an event as specified below − const Button = require(“tns-core-modules/ui/button”).Button; const testButton = new Button(); Step 2 Next add text to the button as specified below − testButton.text = “Click”; Step 3 Create a function, onTap as specified below − let onTap = function(args) { console.log(“you clicked!”); }; Step 4 Now attach tap event to the onTap function as specified below − testButton.on(“tap”, onTap, this); An alternate way to add an event listener is as follows − testButton.addEventListener(“tap”, onTap, this); Step 5 An alternative way to attach event is through UI itself as specified below − <Button text=”click” (tap)=”onTap($event)”></Button> Here, $event is of type EventData. EventData contains two property and they are follows − Object − Observable instance that is used to raise an event. In this scenario, it is Button object. EventName − It is the event name. In this scenario, it is tap event. Step 6 Finally, an event listener can be detached / removed at any time as specified below − testButton.off(Button.onTap); You can also use another format as shown below − testButton.removeEventListener(Button.onTap); Modifying BlankNgApp Let us modify the BlankNgApp application to better understand the events in NativeScript. Step 1 Open the home component’s UI, src/app/home/home.component.html and add below code − <ActionBar> <Label text=”Home”></Label> </ActionBar> <StackLayout> <Button text=”Fire an event” class=”-primary” color=”gray” (tap)=”onButtonTap($event)”></Button> </StackLayout> Here, tap is the event and Button is event raiser. onButtonTap is the event listener. Step 2 Open the home component’s code, ‘src/app/home/home.component.ts’ and update the below code − import { Component, OnInit } from “@angular/core”; import { EventData } from “tns-core-modules/data/observable”; import { Button } from “tns-core-modules/ui/button” @Component({ selector: “Home”, templateUrl: “./home.component.html” }) export class HomeComponent implements OnInit { constructor() { // Use the component constructor to inject providers. } ngOnInit(): void { // Init your component properties here. } onButtonTap(args: EventData): void { console.log(args.eventName); const button = <Button>args.object; console.log(button.text); } } Here, Added new event listener, onButtonTap. Print the event name, tap and button text, Fire an event in the console. Step 3 Run the application and tap the button. It prints the below line in the console. LOG from device <device name>: tap LOG from device <device name>: Fire an event Print Page Previous Next Advertisements ”;