【extjs6学习笔记】1.7 初始:加载第三方库

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

Introduction

Ext JS provides a lot of built-in components right out of the box that are highly customizable. If it‘s not in the framework, you can easily extend the classes or even browse Sencha Market for anything you might need. That works great most of the time, but sometimes you might want to use a 3rd party library that is not built using the Ext JS component system. There are a number of ways you can address this situation, but the easiest one is to create a custom wrapper component to handle your library, which can be reused across any of your apps.

Implementation Overview

The goal of your wrapper component is to encapsulate the logic required by the 3rd party library to set itself up and interact with the Ext JS framework. You have the freedom over how much of that 3rd party API is available to use in your application. There are a few options for how you handle this. If the library is relatively simple and you want to control access to the API, you could wrap each of the API methods with a corresponding method in your wrapper. This allows you to hide methods you don‘t want exposed or intercept method calls where you want to introduce additional custom logic. Another option would be to expose some of the root objects in the API, so other controls are free to call any of the API methods directly on the object. In most cases, this would probably be the approach you‘d end up with, but all projects are different.

To demonstrate this idea, we‘ll create a wrapper component around Leaflet, an open source mapping JavaScript library created by Vladimir Agafonkin. We‘ll use that wrapper component in an app that shows us a map and provides a button to move the map to a specified location.

Leaflet can integrate with mapping tiles from many different mapping services which gives you great flexibility in how your maps look. In this example, we‘ll use some map tiles provided by CloudMade. You can register for a free account there, where you‘ll get an API key to use in your requests (we‘ll use it later in this example). For more information about map tiles, visit the Leaflet site.

Add Library References

The first thing you‘ll need to do in your app is add the library references to your HTML file, so the library will be available for you to use. In our example, we‘ll add two lines to the head per the Leaflet docs. You can get more details on the Leaflet setup 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>

Build the Custom Component

The next thing we‘ll want to do is extend Ext.Component to create the wrapper component for Leaflet. Ext.Component will give us a bare bones control with an empty UI, but it has all the framework methods needed for it to play nice in any of the layouts.

When integrating with a third party library, we typically need to configure and initialize it to match our needs. For our example, we‘re going to handle our Leaflet initialization in an override of the ‘afterRender‘ method. This method runs when our custom component has been rendered to the DOM and is ready for us to interact with. We‘ll also add a class alias and a config variable for our map reference.

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);
                        }
                }
        });

Stepping through the ‘afterRender‘ code:

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

We try to get access to the Leaflet library which is loaded in the window.L namespace. If we can‘t get a reference to the library, we‘ll update the component html with a message stating there was an error loading the library.

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

Here we create a Leaflet map object passing in the ID of the Ext JS component. By default, the HTML tag created by Ext.Component will be a div, which is what Leaflet requires to initialize the map control. Rather than hard code an ID to reference the div, we‘ll use the ID generated by the Ext framework when it renders the control. This will allow us to have multiple instances of the control in our application.

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

This will set the map to the latitude/longitude of the Boston, MA area using a zoom level of 13. There are many online tools for looking up lat/lon‘s for different locations.

this.setMap(map);

Sets the map reference to our map variable so we can access it later.

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 will configure Leaflet to use CloudMade‘s map tiles. Assuming you created an account with them and registered your application, you‘ll get an API key that you will provide in place of ‘YOUR_API_KEY‘. Don‘t worry about the confusing URL, that is how Leaflet will dynamically load your tiles when you move around the map. For additional info, I‘d recommend reviewing the Leaflet API docs.

At this point, you‘ll have a basic mapping control you can use in your applications. However, we‘re not quite done. If you use it as-is, you might not see what you expect. The sizing will not fit your layout. Leaflet requires us to call a method named ‘invalidateSize()‘ any time the map size changes, and it then renders to that size. This is an easy problem to solve in our wrapper component. We can override the ‘onResize‘ method, which gets called anytime the size is changed in the layout, and call the ‘invalidateSize‘ method on the map.

We‘ll add this to our control:

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

This will get called anytime the layout changes, and we‘ll see if we have a valid map reference. If we do, then we‘ll tell Leaflet to ‘invalidateSize‘.

Now we can use the component in our layout, and you can see that it‘ll respect the layout dimensions we‘re providing for it. If the layout changes due to a browser re-size or a slider, you‘ll see the new size get applied. With just a couple lines of code in our custom wrapper component, we‘ve made the third party Leaflet control play nice with the Ext JS layout system.

Sample Usage

Let‘s build a simple Ext JS app that uses this new wrapper 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%‘
                                }
                        ]
                })
        });

This will create a viewport to use the browser‘s full size and render out our map to use the whole view. You should see a large map of the Boston area with some simple zoom controls.

The next thing we‘ll want to do is handle interacting with the map from some outside controls. Let‘s add a button and have it zoom to a location on the map when clicked. According to the Leaflet docs, all you need to do is call ‘setView‘ on the map object, passing in a coordinate array of the latitude/longitude and a zoom level. So all we have to do is have our wrapper component expose the map object we created in ‘afterRender‘, and then we can have the button access that object and call that method on it.

Place this control above our map control in the viewport items array:

{
                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 above code will display a button where when it‘s clicked will try to get a reference to the map object and update it‘s view to a new location. There are many ways to reference a component in an Ext JS application, including Controller refs, Ext.ComponentQuery(), etc. For convenience in this example, we‘ll use a component query to find our map component in this viewport. Once we have the reference, we can call ‘getMap‘ to get the Leaflet map instance and call any Leaflet API methods directly on it.

From here, you can be as fancy as you‘d like your component to get. You can add config properties for all the required setup parameters so you could customize each instance of the component using Ext JS configuration parameters instead of the third party library‘s conventions. You could also add new properties to toggle library features. For example, you could add a property to enable Leaflet‘s ‘locate‘ ability, which will attempt to use your browser‘s Geolocation API to find your location. You can see a more complete example in my GitHub repository.

Conclusion

All libraries are different, and may present additional challenges, but this concept will help you get your Ext JS or Sencha Touch apps integrated with them. There are a number of wrapper components available in the Sencha Market and GitHub already, so you may not need to create your own. But if one doesn‘t exist for a library you need, now you know how to create your own and share it with the rest of the Sencha developer community.

Written by Kevin Kazmierczak

来自 <https://www.sencha.com/blog/integrating-ext-js-with-3rd-party-libraries-2/>

翻译:

http://blog.csdn.net/tianxiaode/article/details/9178861

说明:

官网论坛上描述如下

That‘s a really old blog post you are referring to. Nowadays, preferred way is to reference third party library in app.json. Simply add your 3rd party javascript to JS array and css to CSS array:

Code:

"js": [
{
"path": "app.js",
"bundle": true,
"update": "full"
},
{
"path": "resources/introjs/intro.min.js"
}
],
"css": [
{
"path": "${build.out.css.path}",
"bundle": true,
"exclude": ["fashion"],
"update": "full"
},
{
"path": "resources/introjs/introjs.min.css"
}]

The files will be copied to build folder and loaded automatically when application starts.

来自 <https://www.sencha.com/forum/showthread.php?330047>

时间: 2024-11-03 20:46:16

【extjs6学习笔记】1.7 初始:加载第三方库的相关文章

Openstack学习笔记之——Neutron-server服务加载与启动源码分析(三)

本文是在学习Openstack的过程中整理和总结,由于时间和个人能力有限,错误之处在所难免,欢迎指正! 在Neutron-server服务加载与启动源码分析(二)中搞定模块功能的扩展和加载,我们就回到Neutron-server服务加载与启动源码分析(一)中的_run_wsgi函数 <span style="font-size:14px;">def _run_wsgi(app_name): app = config.load_paste_app(app_name) ifno

Quartz.net 2.x 学习笔记03-使用反射加载定时任务

将定时任务信息存储在XML文件中,使用反射加载定时任务 首先新建一个MVC的空站点,使用NuGet添加对Quartz.net和Common.Logging.Log4Net1213的引用,同时使用NuGet管理器控制台执行命令更新log4net,PM> update-package log4net 接着在解决方案中添加一个类库Library项目 类库项目也添加对Quartz.net的引用 下面可以编写代码了,在Library类库中添加一个JobBase类,3个Job类,和一个Job管理类(假设分别

(Object-C)学习笔记 --OC的懒加载和单例方法

OC的懒加载 什么是懒加载: 懒加载——也称为延迟加载,即在需要的时候才加载(效率低,占用内存小).所谓懒加载,写的是其get方法. 注意:如果是懒加载的话则一定要注意先判断是否已经有了,如果没有那么再去进行实例化. 懒加载的好处 (1)不必将创建对象的代码全部写在viewDidLoad方法中,代码的可读性更强 (2)每个控件的getter方法中分别负责各自的实例化处理,代码彼此之间的独立性强,松耦合 懒加载的例子: #import "MusicTableViewController.h&quo

Laravel 学习笔记之 Composer 自动加载

说明:本文主要以Laravel的容器类Container为例做简单说明Composer的自动加载机制. Composer的自动加载机制 1.初始化一个composer项目 在一个空目录下composer安装Laravel的容器Container包: composer require illuminate/container 然后在该目录下新建一个index.php文件,然后分析下Container类为何能被实例化: <?php /** * Created by PhpStorm. * User:

4月6日学习笔记——如何提高网页加载速度(前端面试考点)

网页的加载速度是评估网站质量一个重要指标.原因在于大多数用户能够容忍的网页加载时间只有几秒,如果超出了访客的忍受范围他们会毫不留情地关掉你的网 页,所以网页载入速度会极大地影响网站的流量和访问.以下总结了几种可以明显提高网站加载速度的初步简单技巧方式,如果你的网站存在载入速度慢的问题不妨 与此为参考对网页做些初步优化. 网页加载提速之 – 优化网页图片文件 你的网页一定有图片,加载一个网页往往图片的总尺寸是最大的,特别是那些颜色丰富的背景图片和大副广告图片.所以一般要在同等图片质量的情况下要尽可

Unity学习笔记13——代码动态加载Prefab预设体

在进行一些功能开发的时候,我们常常将一些能够复用的对象制作成.prefab的预设物体,然后将预设体存放到Resources目录之下,使用时再动态加载到场景中并进行实例化.例如:子弹.特效甚至音频等,都能制作成预设体. 一.预设动态加载到场景: 一个预设体要能够通过代码控制在场景中进行显示,需要三个步骤,这里我们以动态加载怪物血条为例子分析一个常见的误区: 1.预设体资源加载: //加载预设体资源 GameObject hp_bar = (GameObject)Resources.Load("Pr

vue.js学习笔记(二):如何加载本地json文件

在项目开发的过程中,因为无法和后台的数据做交互,所以我们可以自建一个假数据文件(如data.json)到项目文件夹中,这样我们就可以模仿后台的数据进行开发.但是,如何在一个vue.js 项目中引入本地的json文件呢,下面就将步骤贴出来.(此时项目是由webpack打包而成). 整个项目是由webpack打包而成,具体步骤上网查找.具体项目结构如下: 1:我们找到bulid>dev-server.js,然后打开 2:在里面加入这段代码. var app = express() var appDa

学习笔记:python3,PIP安装第三方库(2017)

pip 之于 python 犹如 npm 之于 node.js,亦犹如 package control 之于 Sublime Text 由于python3.4之后的版本都自带了PIP,但是需要升级之后才能使用:C:\Python3\scripts\> python -m pip install --upgrade pip # 查看所安装的package C:\Python3\scripts\> python pip.exe list # 查看某一个package C:\Python3\scri

问题: Octave 改变文件目录后 pkg load 加载第三方库报错

懒得重新安装Octave,就直接从原来安装的目录中复制出来,使用pkg load image命令时会显示报错 pkg load image warning: addpath: "origin path " No such file or direct 显示的路径为原来的路径,应该在某个文件中记录了第一次安装的位置 octave-4.2.0-w64\share\octave\octave_packages 查找替换掉这个文件里所有的原有路径为当前路径即可 From WizNote