路由
var Workspace = Backbone.Router.extend({
routes: {
'help': 'help',
'search/:query': 'search'
},
help:function () {
},
search:function (query,page) {
}
});
路由類的選項
- routes屬性
- 構成方式是鍵值對,當跳轉某頁時,可以監聽
route.on('route.home')
-
constructor/initialize
,使用方式new Backbone.Router([options])
- route方法,
router.route(route,name,callback)
添加路由映射 - naivgate方法,手動跳轉路由
- execute
- 當路由和其響應的callback匹配時被執行
// 手動跳轉路由
app.navigate("help/troubleshooting", {trigger: true, replace: true});
// 在傳遞給你的路由回調之前解析查詢字符串
var Router = Backbone.Router.extend({
execute: function (callback,args) {
// callback是路由匹配后執行的action
// args 是路由上的參數
}
});
路由對象的方法
router.route(route,name,[callback])
- 動態添加路由
- 第一個可以是路由字符串,可以是正則表達式,第二個是路由名稱,第三個是回調函數
router.navigate(fragment,[options])
- 該方法可以動態導航
- 第一個參數,是要導航的地址
- 第二個參數,可以這么設置
-
{trigger: true}
不僅跳轉,還觸發相應action -
{replace: true}
該導航代替當前地址
-
歷史
Backbone.history.start()
- 可以在start中設置參數,
{pushState: true}
,但是要瀏覽器支持h5,同時服務器做相應的配置 - 如果不支持,使用
{hasChange:false}
視圖
視圖創建的選項
-
constructor/initialize
,使用方式new Backbone.View([options])
,這個options
有多個特殊的屬性,如下:
以下幾個選項,定義了視圖掛載的元素,再在render方法中,將該元素動態添加到頁面上。這幾個屬性,在extend中也可以使用
- tagName
- className
- id
- attributes
指定已經存在的掛載元素。這個屬性,在extend中也可以使用
- el
其他
- model
- collection
- events
視圖類中的選項
- template
- events
- render
視圖對象的屬性或者方法
-
view.setElement(element)
動態改變掛載元素 -
view.attributes
此處的屬性指的是,掛載元素上的所有屬性 -
view.$(selector)
當頁面引入jQuery,那么每個視圖都有jQuery選擇器 -
view.remove()
從頁面中移動一個視圖
實用功能
Backbone.onConflict
- 使用CommonJS加載Backbone,必須動態設置
var Backbone.$ = require('jquery');