Integration of Third-Party libraries in ext JS

Source: Internet
Author: User

Address: http://www.sencha.com/blog/integrating-ext-js-with-3rd-party-libraries/

Author:Kevin kazmierczak
Kevin kazmierczak is a senior technical regular ect at Universal Mind, an innovative Digital Solutions agency that fuses the design capabilities of an interactive firm with the technical expertise of a systems integrator. he specializes in building frontend applications using objective-C, HTML/JS, and flex. kevin holds an MBA and a BA in computer science from Alfred University.

Introduction

Ext js provides a large number of highly customizable internal components that can be directly used. If the component is not in the framework, you can easily obtain the required component by extending the class or even browsing the sencha market. This operation may take a lot of time. Sometimes, to save time, you may consider using a third-party library that is not included in the ext JS component system. In this case, there are many solutions, and the simplest way is to create a custom encapsulation component to process the library, so that it can be reused in the application.

Implementation Overview

The purpose of encapsulated components is to encapsulate the logic required by a third-party library for convenient configuration and interaction with the ext JS framework. There is a lot of freedom to use third-party library APIs in applications. If the library is quite simple and you want to control API access, you can encapsulate every method of the API as a corresponding method. In this way, you can hide calls to methods that you do not want to publish or intercept methods when you want to reference additional custom logic. Another method is to expose the root objects in Some APIs so that other controls can freely call any API method through the objects. In most cases, this may be the final solution, but different projects may be different.

To demonstrate this approach, leaflet will create an encapsulated component for leaflet, which is an open-source JavaScript repository created by Vladimir agafonki of the universal mind. In the application, this encapsulation component is used to display a map and a button is provided to move the map to a specified position.

Leaflet can integrate map blocks from many different map services, which provides great flexibility for map display. In the example, the map block provided by cloudmade is used. You can register a free account on the cloudmade website, and then use the obtained API key in subsequent requests (which will be used in the following example. For more information about map blocks, visit the leaflet website.

Add Library Reference

In an application, you must add a library reference to an HTML file to use the library. In the example, add two rows in the head element to reference leaflet. For more details, see the leftlet installation document in the leaflet Quick Start Guide.

<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5/leaflet.css" /><script src="http://cdn.leafletjs.com/leaflet-0.5/leaflet.js"></script>

Create custom components

The next step is to extend the leaflet encapsulation component from Ext. component. Ext. component uses a blank UI to build the control skeleton. However, it provides all the required framework methods so that it can run well in any layout.

When integrating a third-party library, you usually need to configure and initialize it to meet your needs. For the example, You need to override the afterrender method to process leftlet initialization. This method will run after the custom component is rendered to the Dom and ready to interact with the user. You also need to add the alias of the class and the configuration variables for referencing the map.

Ext.define('Ext.ux.LeafletMapView', {extend: 'Ext.Component',alias: 'widget.leafletmapview',config:{map: null},afterRender: function(t, eOpts){this.callParent(arguments); var leafletRef = window.L;if (leafletRef == null){this.update('No leaflet library loaded');} else {var map = L.map(this.getId());map.setView([42.3583, -71.0603], 13);this.setMap(map);L.tileLayer('http://{s}.tile.cloudmade.com/{key}/{styleId}/256/{z}/{x}/{y}.png', {key: 'YOUR_API_KEY',styleId: 997,maxZoom: 18}).addTo(map);}}});

The following describes the afterrender code one by one:

var leafletRef = window.L;if (leafletRef == null){this.update('No leaflet library loaded');} else {....}

Here we try to access the leaflet library in the window. l namespace. If you cannot obtain the reference of the library, use a message to update the HTML of the component, prompting you to encounter an error when loading the library.

var map = L.map(this.getId());

The ID of the ext JS component is passed to create the leftlet map object. By default, the HTML Tag created by Ext. component is Div, which is exactly what leaflet needs to initialize the map component. Here, we use the ID generated by the ext framework when rendering the control, instead of referencing the DIV with a hard-coded ID. The advantage is that you can create multiple instances in the application.

map.setView([42.3583, -71.0603], 13);

In this example, the map is set to the Boston latitude and longitude in Massachusetts, And the scale level of the map is 13. There are many online tools that can be used to find the latitude and longitude of different locations.

this.setMap(map);

Set the map reference to the map variable so that you can use it in subsequent code to access the map.

L.tileLayer('http://{s}.tile.cloudmade.com/{key}/{styleId}/256/{z}/{x}/{y}.png', {key: 'YOUR_API_KEY',styleId: 997,maxZoom: 18}).addTo(map);

This code sets leaflet to use the cloudmade map block. Assuming that you have created an account and registered your application, you can put an API key in your_api_key. Don't worry about the messy website. When moving a map, leaflet dynamically loads the map block. For more information, see the leaflet API documentation.

So far, basic map controls have been created and can be used in applications. However, this is not fully implemented yet. If you use it like this, you will find that it is not the expected effect. The map size does not fill the layout. Leaflet needs to call the invalidatesize () method at any time to adjust the map size and render it to this size. This problem is easily solved in encapsulated components. You can override the onresize method to implement it. In this way, the layout size change can call the invalidatesize method of the map at any time.

Add the following code to the control:

onResize: function(w, h, oW, oH){this.callParent(arguments);var map = this.getMap();if (map){map.invalidateSize();}}

In this way, the layout can be changed and a valid map reference can be called at any time. If the size is adjusted, the leaflet will be told to execute the invalidatesize method.

Now you can use components in the layout, and the map will be displayed in the provided layout size. If the layout changes due to browser size adjustment or slider, a new size is applied to the map. In the custom encapsulation component, after several lines of code, the third-party library leaflet can run well in the ext JS layout system.

Example

Next we will create a simple ext JS application to use this new encapsulated component.

Ext.Loader.setConfig({enabled: true,paths:{'Ext.ux':'ux'}}); Ext.require(['Ext.ux.LeafletMapView']); Ext.onReady(function() {Ext.create('Ext.container.Viewport', {layout: 'vbox',items: [{xtype: 'leafletmapview',flex: 1,width: '100%'}]})});

A viewport is created here to use the size of the entire browser and render the map to the entire view. In this way, you will see a large map of the Boston region and some simple scaling controls.

The next step is to process the interaction between the map and external controls. A button is added below. When you click it, the map is scaled to a position. According to the leaflet document, you need to call the setview method of the map object, and pass the coordinates array and zoom level of the latitude and longitude to it. All you need to do is to publicly encapsulate the map object created by the component in the afterrender method, and then access the object in the button and call its method.

Add the following code to the map component in the items array of viewport:

{xtype: 'button',text: 'Show Buffalo',listeners:{click: function(){var map = Ext.ComponentQuery.query("viewport leafletmapview")[0];map.getMap().setView([42.8864, -78.8786], 13);}}}

The code above will display a button. When you click it, the code will try to get the reference of the map object and update the view to a new location. In ext JS applications, there are many ways to reference components, including controller refs and Ext. componentquery. For the current example, you can use component query to find the map component in the viewport. Once a reference is obtained, you can call the getmap method to obtain the leaflet map instance and directly call any leaflet API method.

From here on, you can implement components as needed. You can add configuration attributes for all the installation parameters, so that you can use the configuration parameters of ext js to replace the conventions of third-party libraries to customize each instance of the component. You can also add new properties to switch the library function. For example, you can add an attribute to enable the location function of leaflet, so that you can find your location through the browser's geolocation API. You can find more complete examples in my GitHub repository.

Summary

All databases are different and more challenges will arise. However, this concept will help to integrate them in ext JS or sencha touch applications. There are already many encapsulated components in the sencha market or GitHub, so you may not need to create your own encapsulated components. If you cannot find the required library, you need to create your own encapsulated component and share it with the sencha development community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.