语言: ENCN

初始化应用

你已经有了基本的页面布局和需要用的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
materialPreloaderHtml string '<span class="preloader-inner"><span class="preloader-inner-gap"></span><span class="preloader-inner-left"><span class="preloader-inner-half-circle"></span></span><span class="preloader-inner-right"><span class="preloader-inner-half-circle"></span></span></span>' HTML of Material's theme 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 Set to false if you want to disable animated transitions between pages
preloadPreviousPage boolean true Enable/disable preloading of previous page when you go deep in navigation. Should be enabled for correct work of "swipe back page" feature.
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 If you develop web app (not PhoneGap or Home Screen web app) it is useful to enable hash navigation (browser url will look like "http://my-webapp.com/#/about.html"). User as well will be able to navigate through app's history by using browser's default back and forward buttons.
pushStateSeparator string '#!/' Push state URL separator, can be changed for something like '#page/' and then your push state urls will look like "http://myapp.com/#page/about.html"
pushStateRoot string undefined Push state root URL separator, for example "http://my-app.com/". It is useful only in case when you use empty ("") pushStateSeparator
pushStateNoAnimation boolean false If false then it will inherit View's animatePages parameter. If true, then push state navigation will happen without animation (page transitions)
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
Swipe back (iOS theme only)
swipeBackPage boolean true Enable/disable ability to swipe back from left edge of screen to get to the previous page.
swipeBackPageThreshold number 0 Value in px. Swipe back action will start if "touch distance" will be more than this value.
swipeBackPageActiveArea number 30 Value in px. Width of invisible left edge of the screen that triggers swipe back action
swipeBackPageAnimateShadow boolean true Enable/disable box-shadow animation during swipe back action. You can disable it to improve performance
swipeBackPageAnimateOpacity boolean true Enable/disable opacity animation during swipe back action. You can disable it to improve performance
Sortable Lists
sortable boolean true If you don't use sortable lists you can disable it for potentially better performance.
Swipeout
swipeout boolean true If you don't use swipeouts you can disable this feature for potentially better performance.
swipeoutNoFollow boolean false Fallback option for potentially better performance on old/slow devices. If you enable it, then swipeout item will not follow your finger during touch, it will be automatically opened/closed on swipe left/right.
Side Panels
swipePanel string false Disabled by default. If you want to enable ability to open side panels with swipe you can pass here "left" (for left panel) or "right" (for 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 Fallback option for potentially better performance on old/slow devices. If you enable it, then side panel will not follow your finger during touch, it will be automatically opened/closed on swipe left/right.
swipePanelThreshold number 0 Value in px. Panel will not move with swipe if "touch distance" will be less than this value.
panelsCloseByOutside boolean true Enable/disable ability to close panel by clicking outside of panel (on panel's overlay)
Modals
modalTitle string 'Framework7' Default title for modals (Alert, Confirm, Prompt)
modalButtonOk string 'OK' Default text for modal's "OK" button
modalButtonCancel string 'Cancel' Default text for modal's "Cancel" button
modalPreloaderTitle string 'Loading... ' Default text for preloader modal
modalCloseByOutside boolean false Enable/disable ability to close modal (Alert, Confirm, Prompt) by clicking outside of modal (on modal's overlay)
actionsCloseByOutside boolean true The same as previous but for Action Sheet modal
popupCloseByOutside boolean true The same as previous but for Popup modal
modalTemplate string undefined Full HTML Template7 formatted HTML template for modals (like alert, confirm and prompt). Look at the example of 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' Place holder text for username input in Login Modal
modalPasswordPlaceholder string 'Password' Place holder text for password input in Login and 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
smartSelectOpenIn string 'page' Specify default way of how Smart Select should be opened. Can be 'page', 'popup' or 'picker'
smartSelectBackTemplate string '<div class="left sliding"><a href="#" class="back link"><i class="icon icon-back"></i><span>{{backText}}</span></a></div>' Smart Select page navbar back link HTML template
smartSelectPopupCloseTemplate string '<div class="left"><a href="#" class="link close-popup"><i class="icon icon-back"></i><span>{{closeText}}</span></a></div>' Smart Select popup close link HTML template
smartSelectBackText string 'Back' Default back link text for Smart Select's page navbar
smartSelectPopupCloseText string 'Close' Default close link text for Smart Select's popup navbar
smartSelectPickerCloseText string 'Done' Default close link text for Smart Select's picker toolbar
smartSelectSearchbar boolean false Set to true if you want to enable Search Bar for all Smart Selects
smartSelectBackOnSelect boolean false If enabled then smart select page will be automatically closed after user picks any option
smartSelectFormTheme string undefined One of 10 default color themes for form elements on smart select page/popup
smartSelectNavbarTheme string undefined One of 10 default color themes for navbar on smart select page/popup
Navbars / Toolbars
hideNavbarOnPageScroll boolean false Set to true and Navbar will be hidden automatically on page scroll down, and become visible on scroll up
hideToolbarOnPageScroll boolean false Set to true and Toolbar will be hidden automatically on page scroll down, and become visible on scroll up
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 Set to true to show hidden Navbar and Toolbar when scrolling reaches end of the page
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 Default title for all notifications iOS theme only
notificationSubtitle string undefined Default subtitle for all notifications iOS theme only
notificationMedia string undefined Default media (icon or image) for all notifications iOS theme only
notificationHold number undefined Default hold duration (in ms) for all notifications
notificationCloseOnClick boolean false Set to true if you want to close notification on click by default
notificationCloseIcon boolean true Set to true if you want to display close icon (button) for notifications by default 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 Set to true to enable Template7 rendering for Ajax and Dynamic pages. Learn more about it in Template7 Pages section
template7Data object {} Parameter to store templates/pages data for Template7 rendering. Learn more about it in Template7 Pages section
precompileTemplates boolean false With this option you may framework will compile all Template7 templates automatically. Learn more about Templates Auto Compilation section
templates object {} Object with compiled Template7 templates. Learn more about it in Templates Auto Compilation section
Page Callbacks
onPageBeforeInit function(app, page) - Callback function that will be executed when Framework7 just inserts new page to DOM. Does the same as "pageBeforeInit" page event
onPageInit function(app, page) - Callback function that will be executed when Framework7 initialize required page's components and navbar. Does the same as "pageInit" page event
onPageBeforeAnimation function(app, page) - Callback function that will be executed when everything initialized and page (and navbar) is ready to be animated. Does the same as "pageBeforeAnimation" page event
onPageAfterAnimation function(app, page) - Callback function that will be executed after page (and navbar) animation. Does the same as "pageAfterAnimation" page event
onPageBeforeRemove function(app, page) - Callback function that will be executed right before page will be removed from DOM. Does the same as "pageBeforeRemove" page event
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 Callbacks
onAjaxStart function(xhr) - Callback function that will be executed in the beginning of Ajax request. This function accepts xhr data as an argument.
onAjaxComplete function(xhr) - Callback function that will be executed after Ajax request. This function accepts xhr data as an argument.
Namespace

Attention! If you change following class names you will also need to change them in CSS!

viewClass string 'view' Class name for your View element
viewMainClass string 'view-main' Class name for your Main View element
viewsClass string 'views' Class name for your Views element
Init
init boolean true By default Framework7 will be initialized automatically when you call new Framework7(). If you want to prevent this behavior you can disable it with this option and then initialize it manually with myApp.init() when you need it.

So your final initialization code in my-app.js could look like:

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

Example with "preprocess" content

Framework7 allows you to use your favorite client-side template engine or do any modifications with loaded content.

Let's look on how to init app with usage of Template7 as our client-side template engine

Init app in my-app.js:

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>   

But sometimes you may have asynchronous thread inside of your preprocess functon, for example if you need to do one more Ajax request and only after that to continue page loading. For this case we have "next" callback function where we need to pass our genereated/modified content:

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

Example with "preroute"

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

For example we can check if the user is not logged in when he requesting some page and then to redirect him to the login page

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

What's next

Ok, right after we initialize our App we need to add and initialize Views