Backbone核心模块:model/view/Collection/router
- model 负责数据&逻辑
- view 负责视图表现
- collection 作为一个model集合
- router负责路由切换
Model
- 初始化 initialize
- 默认值 defaults
- 校验 validate仅默认在save时执行,若想set也执行校验需要添加{validate:true};
- 和服务器交互 url save fetch
var hello =Backbone.Model.extend({ url:'/man/', //用于CRUD,删除时需要传入id,则应该指定urlRoot initialize:function(){ console.log('初始化操作,首先执行。。'); //监听name改变状态 this.on('change:name',function(){ alert('name changed!!!'); }, //invalid事件传递三个参数(model, error, options) this.on('invalid',function(model,err){ alert(err); }) }, defaults:{ name:'jack', age:18 }, validate:function(attributes){ if(attributes.name ==''){ return "name不能为空"; } } })
collection
可以理解为model集合
var Book=Backbone.Model.extend({ });var BookShelf =Backbone.Collection.extend({ model:Book, url:'/books/'})BookShelf.fetch({ reset:true//重置集合,重新填充 success:function(collection,res,options){ },error:function(collection,res,options){ }})//新建记录BookShelf.create({ title:'hahah'})
Router
页面加载期间,当应用创建了所有的路由,需要调用Backbone.history.start()或者Backbone.history.start({pushState:true})来确保初始化路由;
route匹配原则:(/可以匹配#和标准url(/))
- *,匹配所有 //*actions
- :匹配参数 // /post/:id
"post" :"post //#post "post/:id":"save" //#post/:id "post/12/:page" :"pageChange" //#post/12/12
var AppRouter =Backbone.Router.extend({
routes:{ //匹配所有请求,执行defaultRoute函数 "*actions" :"defaultRoute" }, defaultRoute:function(actions){ alert(actions) } }); var myRouter =new AppRouter; Backbone.history.start(); myRouter.navigate('/post/',{trigger:true,replace:true}); trigger,返回true触发事件,返回false只是url变化,不触发事件 replace ,替换url,history不会记录变动
View
var MyView =Backbone.View.extend({
//引用dom元素,可以显示声明(没显示声明会构造一个空div)也可以在构造函数中传递, el:$('#myView'), initialize:function(){ console.log('it's my view'); }, render:function(context){ var template =_.template($('#search_template').html()); $(this.el).html(template(context)); }, events:{ //在el范围内查找元素,绑定点击事件, 'click input[type=button]' : 'showName' } , doSearch:function() {
}
})
var myView =new MyView({el:$('#myView')});//构造函数中声明 myView.render({name:'jack'}) //初始化时自动渲染