dd

初始化应用


你已经有了基本的页面布局和需要用的CSS以及JS文件。现在我们需要初始化我们的应用,比如在 my-app.js

var myApp = new Framework7();

上面这个例子中我们使用了 myApp 作为变量名存储 Framework7 初始化之后的实例。

这样初始化非常简单,但是Framework7 也提供了更多个性化的定制,只需要在初始化的时候传入一个配置对象即可。

var myApp = new Framework7({
    pushState: true,
    swipePanel: 'left',
    // ... other parameters
});

下面是这个变量的列表:

参数 类型 默认值 说明
Material Theme (Material theme only)
material boolean false Set to true to activate Material-specific App JS behavior
materialPageLoadDelay number 0 Delay (in ms) before animation of loaded page. Can be increased a bit to improve performance
materialRipple boolean true Enable/disable Material-specific touch ripple effect
materialRippleElements string '.ripple, a.link, a.item-link, .button, .modal-button, .tab-link, .label-radio, .label-checkbox, .actions-modal-button, a.searchbar-clear, .floating-button' CSS selector of elements to apply touch ripple effect on click
materialPreloaderSvg string '<svg xmlns="http://www.w3.org/2000/svg" height="75" width="75" viewbox="0 0 75 75"><circle cx="37.5" cy="37.5" r="33.5" stroke-width="8"/></svg>' HTML of Material' theme SVG preloader
Caching
cache boolean true 是否打开 Ajax 缓存,因为Framework7使用ajax加载新页面,最好启用Ajax缓存,特别是你的页面内容不经常更新的时候。
cacheDuration number 1000*60*10 Ajax 缓存时间,在缓存有效期内加载页面不会发起新的ajax请求而是直接使用缓存的结果。默认是10分钟。
cacheIgnore array [] 不希望被缓存的URL,这是一个字符串数组。
cacheIgnoreGetParameters boolean false 缓存是否忽略get参数,如果为 "true",那么像 "about.html?id=2" 和 "about.html?id=3" 将会和 "about.html" 是一样的缓存。
快速点击(Fast clicks library)
fastClicks boolean true Fast clicks 是一个内置库,当你点击链接或者提交表单的时候,她会移除300毫秒的延迟。如果你有其他的 fast click 库,你可以禁用这个功能。
fastClicksDelayBetweenClicks number 50 Minimal allowed delay (in ms) between miltiple clicks
fastClicksDistanceThreshold number 10 需要阻止tab事件的距离。当 tap/move 的距离超过这个值的时候,不会触发click事件。
activeState boolean true 启用这个设置时,会给当前点击的元素增加一个 'active-state' class。
activeStateElemets string 'a, button, label, span' 应该在这些元素上加 activeState
tapHold boolean false Set to true to enable tap hold events
tapHoldDelay number 750 Determines how long (in ms) the user must hold their tap before the taphold event is fired on the target element
tapHoldPreventClicks boolean true When enabled (by default), then click event will not be fired after tap hold event
Navigation / Router
router boolean true 如果你有自己的路由实现,你可以禁用默认的路由
ajaxLinks string undefined 指定哪些链接需要用ajax加载,默认情况下(当为undefined时)Framework7 会使用ajax加载所有的链接。你可以通过设置一个CSS选择器来指定需要通过Ajax加载的链接,比如 "a.ajax" - 只有class 为 "ajax" 的链接。
dynamicPageUrl string 'content-{{index}}' URL rule for dynamically loaded pages. Available replaceable expressions: '{{index}}' (page index number in navigation history) and '{{name}}' (value of page "data-page" attribute)
uniqueHistory boolean false Set to true and App will keep View's navigation history unique, it will also remove duplicated pages
uniqueHistoryIgnoreGetParameters boolean false Use this parameter in addition to uniqueHistory. Set to true and App will ignore URL GET parameters when cheking its uniqueness. So the URLs like "page.html" and "page.html?id=3" will be treated as the same.
externalLinks string '.external' 不应该被 Framework7 管理的链接的CSS选择器。比如 ".external" 会匹配到这样的链接 <a href="somepage.html" class="external"> (因为它有 "external" 类)
allowDuplicateUrls boolean false You may enable this parameter to allow loading of new pages that have same url as currently "active" page in View.
animateNavBackIcon boolean false 当启用这个功能时,动态导航栏中的 back-link 图标的动画会更接近iOS的风格。只有当你使用动态导航栏并且使用了默认的 back-link 图标时才应该把这个值设置为 "sliding"。 iOS theme only
animatePages boolean true 如果你想禁用页面切换的动画,就把这个值设置为 false。
preloadPreviousPage boolean true 预加载上一页,为了能让"滑动返回上一页"功能正常工作,这个值应该设置为 true。
preroute function(view, options) -

This callback allows to prevent default router load/back actions and to load another page or do another required actions

Look for example below

preprocess function(content, url, next) -

This callback function allows you to modify loaded router (mostly Ajax) content right before it will be injected to DOM. Callback receives "content" and "url" of the loaded page and the "next" callback function. After you modify content within this function you should return it with: return content

Look for example below

Push State
pushState boolean false 如果你开发web app(而不是通过PhoneGap封装的混合应用),那么这个功能将很有用(浏览器的URL将会看上去像这样 "http://my-webapp.com/#/about.html")。用户可以通过浏览器默认的前进后退按钮来操作。
pushStateSeparator string '#!/' push state 时候在URL中使用的分隔符,如果改成 "#page/",那么你的url将会像这样 "http://myapp.com/#page/about.html"
pushStateRoot string undefined Push state URL根路径, 比如 "http://my-app.com/". 只有当你把 pushStateSeparator 设置为空("")时才有效。
pushStateNoAnimation boolean false 如果设置为 false,那么会继承当前 View 的 animatePages 参数。如果设置为 true,那么页面切换的时候将没有动画效果。
pushStatePreventOnLoad boolean true If enabled, the first pop state event on app load will be ignored, as it can casue issues that load unnecessary. But useful to disable when you init app using async loaders like Require.js
滑动返回上一页(iOS theme only)
swipeBackPage boolean true 开启/关闭滑动返回上一页功能。
swipeBackPageThreshold number 0 单位px,当滑动距离超过这个数值的时候,滑动返回上一步功能就会生效。
swipeBackPageActiveArea number 30 Value in px. Width of invisible left edge of the screen that triggers swipe back action
swipeBackPageAnimateShadow boolean true 打开/关闭 滑动返回时候的 box-shadow 动画。关闭这个功能可以提高性能。
swipeBackPageAnimateOpacity boolean true 打开/关闭 滑动返回时候的半透明效果。关闭这个功能可以提高性能。
可排序列表(Sortable Lists)
sortable boolean true 如果你不使用可排序列表,可以禁用这个功能。因为禁用之后可能会有潜在的性能提升。
滑动删除(swipeout)
swipeout boolean true 如果你使用滑动删除,禁用这个选项,可能会带来潜在的性能提升。
swipeoutNoFollow boolean false 滑动删除的时候动画是否跟随手指移动,如果设置为true,那么你滑动的时候动画会自动开始/结束,而不是跟随你手指的位置,这样在老的设备上可能会有更好性能。
Side Panels
swipePanel string false 默认是禁用的,如果你希望通过滑动可以打开 side panel,那么可以设置为 "left" (lef panel) 或者 "right" ( right panel)
swipePanelCloseOpposite boolean true This parameter gives ability to close opposite panel by swipe. For example, if your swipePanel is "left", then you could close "right" panel also with swipe.
swipePanelOnlyClose boolean false This parameter allows to close (but not open) panels with swipes
swipePanelActiveArea number false Value in px. Width of invisible edge from the screen that triggers swipe panel
swipePanelNoFollow boolean false 为了兼容老的设备。当设置为 true时,side panel的动画不会跟随你的手指,而是自动开始/结束。
swipePanelThreshold number 0 Value in px. Panel will not move with swipe if "touch distance" will be less than this value.
panelsCloseByOutside boolean true 点击 panel 外面来关闭她。
弹层(Modals)
modalTitle string 'Framework7' 默认的标题 (Alert, Confirm, Prompt)
modalButtonOk string 'OK' 确定按钮的默认文案
modalButtonCancel string 'Cancel' 取消按钮的默认文案
modalPreloaderTitle string 'Loading... ' 默认的加载提示文案
modalCloseByOutside boolean false 点击modal(Alert, Confirm, Prompt)外面关闭她。
actionsCloseByOutside boolean true 和上面一样,但是是针对 Action Sheet 的
popupCloseByOutside boolean true 和上面一样但是针对 popup 的
modalTemplate string undefined 弹层(alert, confirm and prompt) 对应的 Template7 模板。参见Modal Template
modalActionsTemplate string undefined Template7 formatted HTML template for Action Sheet. Could be useful if you want to add some custom elements to Action Sheet layout. Look at the example of Action Sheet Template
modalActionsToPopoverTemplate string Template7 formatted HTML template for Action Sheet that will be converted to Popover. Could be useful if you want to add some custom elements to Popover layout. Look at the example of Action Sheet To Popover Template
modalUsernamePlaceholder string 'Username' 在Login Modal中,username输入框的占位符
modalPasswordPlaceholder string 'Password' 在 Login 和 Password Modals 中密码输入框的占位符
modalStack boolean true This feature doesn't allow to open multiple modals at the same time, and will automatically open next modal when you close the current one. Such behavior is similar to browser native alerts
Smart Select
smartSelectInPopup boolean false Set to true and all Smart Selects, by default, will be opened as popup
smartSelectBackTemplate string '<div class="left sliding"><a href="#" class="back link"><i class="icon icon-back"></i><span>{{backText}}</span></a></div>' Smart select 页面模式中导航栏中的返回按钮的HTML模板
smartSelectPopupCloseTemplate string '<div class="left"><a href="#" class="link close-popup"><i class="icon icon-back"></i><span>{{closeText}}</span></a></div>' Smart Select 弹层方式中关闭链接的 HTML template
smartSelectBackText string 'Back' Smart select 页面导航栏中的返回按钮的文案
smartSelectPopupCloseText string 'Close' Default close link text for Smart Select's popup navbar
smartSelectSearchbar boolean false 所有的 Smart Selects 打开/关闭搜索功能。
smartSelectBackOnSelect boolean false 在 smart select 页面选择任何条目之后立刻返回。
smartSelectFormTheme string undefined smart select 页面/弹层中 使用的主题,是十个默认的颜色主题中的一个。
smartSelectNavbarTheme string undefined smart select 页面/弹层中的导航栏主题,是十个默认的颜色主题中的一个。
导航栏和工具栏(Navbars / Toolbars)
hideNavbarOnPageScroll boolean false 设置为true,那么当页面向下滚动的时候,导航栏会自动隐藏;向上滚动的时候会自动出现。
hideToolbarOnPageScroll boolean false 设置为true,那么当页面向下滚动的时候,工具栏会自动隐藏;向上滚动的时候会自动出现。
hideTabbarOnPageScroll boolean false Set to true and Tab bar will be hidden automatically on page scroll down, and become visible on scroll up. Note that this is only for Tab Bar app layout, otherwise use hideToolbarOnPageScroll
showBarsOnPageScrollEnd boolean true 设置为true,那么当页面滚动到底部的时候会自动显示出被隐藏的导航栏和工具栏。
showBarsOnPageScrollTop boolean true Set to false and bars will not become visible when you scroll page to top everytime. They will become visible only on the most top scroll position, in the beginning of the page
scrollTopOnNavbarClick boolean false Set to true and each click on Navbar's "center" element will scroll currently active page to top
Images Lazy Load
imagesLazyLoadThreshold number 0 By default images are loaded when they appear on the screen. Use this parameter if you want to load images earlier. Setting it to 50 will load image when it 50 pixels before it appears on viewport
imagesLazyLoadSequential boolean true If enabled, then lazy images will be loaded one by one when they appear in viewport
imagesLazyLoadPlaceholder string Lazy load image placeholder source to show while image is not yet loaded. By default it is 1x1 px image
Notifications
notificationTitle string undefined 所有通知(notifications)的默认标题iOS theme only
notificationSubtitle string undefined 所有通知(notifications)的默认副标题iOS theme only
notificationMedia string undefined 所有通知(notifications)的默认图标iOS theme only
notificationHold number undefined 所有通知(notifications)的默认显示时间
notificationCloseOnClick boolean false 设置为true之后,点击就可以关闭通知
notificationCloseIcon boolean true 设置为true,则默认就会显示一个关闭按钮iOS theme only
notificationCloseButtonText string 'Close' Default text for Snackbars' close button Material theme only
状态栏(Status Bar)iOS theme only
statusbarOverlay boolean undefined With this option you can overwrite automatic status bar detection
scrollTopOnStatusbarClick boolean false Set to true and each click on Status bar ("status-bar-overlay") will scroll currently active page to top
Template7
template7Pages boolean false 设置为true,则会自动使用 Template7 来渲染 ajax或者动态生成的页面。这里有更详细的说明 Template7 Pages
template7Data object {} 用来存储Template7 渲染页面所需的数据。这里有更详细的说明:Template7 Pages
precompileTemplates boolean false 是否自动编译所有的 Template7 模板。这里有更详细的说明:Templates Auto Compilation
templates object {} 编译好的 Template7 模板。这里有更详细的说明:Templates Auto Compilation
页面回调(Page Callbacks)
onPageBeforeInit function(app, page) - 回调函数,当Framework7把新页面插入到DOM的时候会触发这个回调。和 page event 中的 "pageBeforeInit" 是一样的。
onPageInit function(app, page) - 回调函数,当Framework7初始化页面的组件的时候会调用这个回调。 和 page event 中的 "pageInit"事件是相同的作用
onPageBeforeAnimation function(app, page) - 回调函数,当页面全部初始化完成之后并且准备好开始做动画的时候会调用此回调。和page event 中的 "pageBeforeAnimation" 是一样的。
onPageAfterAnimation function(app, page) - 回调函数,当页面动画结束的时候调用。和 page event 中的 "pageAfterAnimation" 是相同的作用
onPageBeforeRemove function(app, page) - 回调函数,当页面从DOM中移除的时候调用。和 page event 中的 "pageBeforeRemove" 是相同的作用
onPageBack function(app, page) - Callback function that will be executed right before "back" transition. Difference with "onPageBeforeAnimation" is that this callback will be executed for the "old" page - page that slides from center to right. Does the same as "pageBack" page event
onPageAfterBack function(app, page) - Callback function that will be executed right after "back" transition. Difference with "onPageAfterAnimation" is that this callback will be executed for the "old" page - page that slides from center to right. Does the same as "pageAfterBack" page event
Ajax回调函数(Ajax Callbacks)
onAjaxStart function(xhr) - 当Ajax请求开始的时候调用,这个函数会传递一个 xhr 对象作为参数。
onAjaxComplete function(xhr) - Ajax 请求结束的时候调用。会传递一个xhr对象作为参数。
命名空间

注意!如果你改变了命名空间,记得也要改CSS中对应的class!

viewClass string 'view' View 元素对应的class
viewMainClass string 'view-main' main view 元素对应的 class
viewsClass string 'views' views 元素对应的class
初始化(Init)
init boolean true 默认情况下,当你调用 new Framework7() 的时候Framework7会自动初始化。如果你希望自己手动控制,那么你可以禁用这个选项,然后自己调用 myApp.init()来初始化。

最终你写在 my-app.js 中的代码可能会是这样的:

var myApp = new Framework7({
    // Default title for modals
    modalTitle: 'My App',
 
    // If it is webapp, we can enable hash navigation:
    pushState: true,
 
    // Hide and show indicator during ajax requests
    onAjaxStart: function (xhr) {
        myApp.showIndicator();
    },
    onAjaxComplete: function (xhr) {
        myApp.hideIndicator();
    }
});   

预处理内容

Framework 可以让你用自己喜欢的客户端模板引擎,或者在内容加载之后再做任意修改。

让我们看看如何在初始化应用的时候把 Template7 当做我们自己的客户端模板引擎。

var myApp = new Framework7({
    preprocess: function (content, url, next) {
        if (url === 'people.html') {
            var template = Template7.compile(content);
            var resultContent = template({
                title: 'People',
                people: ['John', 'Ivan', 'Mary']
            })
            return resultContent;
        }
    }
});

And the people.html page:

<div class="navbar">
  <div class="navbar-inner">
    <div class="center">{{title}}</div>
  </div>
</div>
<div class="pages">
  <div data-page="people" class="page">
    <div class="page-content">
      <ul>
        {{#each people}}
        <li>{{this}}</li>
        {{/each}}
      </ul>
    </div>
  </div>
</div>

有时候你会在预处理方法中有一些异步的逻辑,比如你用ajax来加载页面。这种情况下,我们提供了 "next" 回调函数,用来传入我们编译或者修改后的内容:

var myApp = new Framework7({
    preprocess: function (content, url, next) {
        if (url === 'people.html') {
            // For example, we will retreive template JSON data using Ajax and only after that we will continue page loading process
            $$.get('sometemplate.html', function(data) {
                // Template
                var template = Template7.compile(content);
 
                // Compile content template with received JSON data
                var resultContent = template(data);
 
                // Now we call "next" callback function with result content
                next(resultContent);
            });
            // Now we shouldn't return anything
        }
    }
});          

"prerouter" 示例

这个回调函数可以用来阻止路由器默认的 加载/返回 行为,你可以自己去加载其他页面,重定向,或者做任意你需要的操作。

比如我们在用户访问某些页面的时候可以去检查他是否登录,如果未登录就跳转到登录页面

var myApp = new Framework7({
    preroute: function (view, options) {
        if (!userLoggedIn) {
            view.router.loadPage('auth.html'); //load another page with auth form
            return false; //required to prevent default router action
        }
    }
});

下一步

在初始化应用之后,我们需要添加并初始化 视图