Sencha Touch 2天气应用开发实战与优化技巧
1. 项目概述构建Sencha Touch 2天气应用的关键阶段这个系列教程的第三部分将带您深入Sencha Touch 2框架的核心功能实现。不同于前两篇的基础搭建和界面设计本篇聚焦于将静态页面转化为真正可用的天气应用。作为移动端混合开发的老兵我认为这个阶段是最能体现Sencha Touch价值的环节——通过JavaScript API实现复杂业务逻辑同时保持原生应用般的用户体验。在2013年Sencha Touch 2的全盛时期这类天气应用是展示框架能力的经典案例。它需要处理三个关键技术点跨平台UI适配、动态数据获取与解析、本地存储优化。即便放到今天这些技术要点仍然是移动开发的必修课。2. 核心架构解析2.1 MVC模式在天气应用中的实践Sencha Touch强制采用MVC架构这在天气应用中体现得尤为明显。我的项目结构通常这样组织app/ ├── controller/ │ └── Weather.js ├── model/ │ └── City.js ├── store/ │ ├── Cities.js │ └── Forecast.js └── view/ ├── Main.js └── forecast/ ├── Daily.js └── Detail.js控制器(Weather.js)需要处理两个核心事件城市选择变化时的数据刷新下拉刷新的手势处理经验之谈永远在controller的init方法中初始化事件监听而不是在launch方法里。这样可以避免移动设备上偶发的事件丢失问题。2.2 数据层设计要点天气应用的数据源通常来自第三方API如OpenWeatherMap。在model设计中我推荐采用嵌套模型的方式Ext.define(WeatherApp.model.Forecast, { extend: Ext.data.Model, config: { fields: [ {name: date, type: date}, {name: temp, type: int}, {name: conditions, type: string} ], hasMany: { model: WeatherApp.model.Hourly, name: hourly } } });存储层(Cities.js)的配置需要特别注意分页和自动加载pageSize: 10, autoLoad: false, remoteFilter: true, proxy: { type: ajax, url: /api/cities, reader: { type: json, rootProperty: data } }3. 关键功能实现3.1 天气数据获取与缓存实际项目中我总结出三种数据获取策略基础方案简单AJAX请求Ext.Ajax.request({ url: https://api.weather.com/v3/..., params: { apiKey: YOUR_KEY, geocode: ${lat},${lng} }, success: function(response) { // 处理数据 } });推荐方案通过Store管理Ext.create(Ext.data.Store, { model: WeatherApp.model.Forecast, proxy: { type: jsonp, url: https://api.weather.com/v3/..., reader: { type: json, rootProperty: daily } }, autoLoad: true });高级方案本地存储定时更新// 优先读取本地数据 var cachedData localStorage.getItem(weatherData); if(cachedData) { updateUI(Ext.JSON.decode(cachedData)); } // 后台更新 setInterval(function() { fetchNewData().then(function(data){ localStorage.setItem(weatherData, Ext.JSON.encode(data)); }); }, 3600000); // 每小时更新3.2 复杂UI组件实现天气应用需要展示多种数据形式我的组件方案是主界面布局使用TabPanel组织不同视图Ext.create(Ext.TabPanel, { fullscreen: true, tabBarPosition: bottom, items: [{ title: 当前天气, iconCls: home, xtype: currentView },{ title: 预报, iconCls: calendar, xtype: forecastView }] });天气图表自定义Component绘制Ext.define(WeatherApp.view.Chart, { extend: Ext.Component, config: { tpl: [ canvas id{id}-canvas width300 height200/canvas ], data: {} }, initialize: function() { this.callParent(); this.canvas Ext.get(this.getId() -canvas).dom; this.ctx this.canvas.getContext(2d); this.drawChart(); }, drawChart: function() { // 使用Canvas API绘制温度曲线 } });4. 性能优化实战4.1 列表渲染优化天气预报列表是性能瓶颈我的解决方案是启用itemCacheExt.create(Ext.List, { // ... itemCache: true, variableHeights: false });简化模板复杂度itemTpl: [ div classforecast-item, div classdate{date:date(m/d)}/div, div classtemp{temp}°/div, /div ]4.2 内存管理Sencha Touch应用常见的内存泄漏问题可以通过以下方式避免及时销毁弹出组件var popup Ext.create(Ext.Panel, { // ... listeners: { hide: function() { Ext.defer(function(){ popup.destroy(); }, 1000); } } });合理使用事件解绑control: { button[actionrefresh]: { tap: onRefresh } }, onRefresh: function() { // 处理逻辑 }, destroy: function() { this.uncontrol(); // 重要 this.callParent(); }5. 跨平台适配技巧5.1 平台特定样式在app.json中配置平台差异化资源css: [ { path: resources/css/app.css, platform: [chrome, safari] }, { path: resources/css/android.css, platform: [android] } ]5.2 设备特性检测if(Ext.os.is.Android) { // Android特有逻辑 } else if(Ext.os.is.iOS) { // iOS特有逻辑 } if(Ext.feature.has.Geolocation) { navigator.geolocation.getCurrentPosition(function(pos){ // 获取位置 }); }6. 调试与发布6.1 远程调试方案iOSSafari Web InspectorAndroidChrome远程调试通用方案Weinrenpm install -g weinre weinre --boundHost -all-6.2 打包优化在app.json中配置构建参数builds: { production: { packager: cordova, cordova: { config: { platforms: ios android, id: com.yourcompany.weatherapp } } } }构建命令sencha app build production7. 经验总结与常见问题7.1 性能陷阱过度嵌套的容器使用xtype而非create嵌套频繁的DOM操作善用数据绑定未压缩的资源确保启用production构建7.2 调试技巧开启Sencha Touch调试模式Ext.Loader.setConfig({ enabled: true, paths: { Ext: touch/src } });查看组件树Ext.Viewport.down(tabpanel).getItems().items7.3 Cordova集成要点插件安装顺序很重要cordova plugin add cordova-plugin-geolocation cordova plugin add cordova-plugin-splashscreenconfig.xml关键配置preference nameDisallowOverscroll valuetrue/ preference nameUIWebViewBounce valuefalse/在真实项目中我发现Sencha Touch 2的曲线图表现不佳最终采用了Highcharts Mobile作为替代方案。这种框架组合方案在多个商业项目中验证通过能够实现60fps的流畅动画效果。