首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

Backbone.js引见

2012-09-03 
Backbone.js介绍注:教程请参见这里(本文有很多内容都是从这里翻译的),官方网站在这里;综合例子参见这里。?B

Backbone.js介绍

注:教程请参见这里(本文有很多内容都是从这里翻译的),官方网站在这里;综合例子参见这里。

?

Backbone.js是一个前端MVC框架,model能够绑定键值对和自定义事件,集合具备可枚举方法的富API,视图具备事件处理能力,并且可以通过RESTful的JSON接口和你已有的API通信。

?

View

?

Backbone里的视图就是用来反映数据模型的,可以监听事件并响应,通过利用Underscore.js(这个真是一个牛逼哄哄的东西,自己看),还支持了JavaScript模板技术,把数据和模板分离开。

?

“el”熟悉就是浏览器创建的一个DOM对象的引用,是供backbone渲染的画布,每一个view都会有这样一个属性,如果不存在,backbone就会自己定义一个空的div来作为el,现在把"el"属性定义到div#search_container,看:

?

<div id="search_container"></div><script type="text/javascript">     SearchView = Backbone.View.extend({        initialize: function(){            this.render();        },        render: function(){            //Pass variables in using Underscore.js Template            var variables = { search_label: "My Search" };            // Compile the template using underscore            var template = _.template( $("#search_template").html(), variables );            // Load the compiled HTML into the Backbone "el"            this.el.html( template );        },        events: {            "click input[type=button]": "doSearch"          },        doSearch: function( event ){            // Button clicked, you can access the element that was clicked with event.currentTarget            alert( "Search for " + $("#search_input").val() );        }    });            var search_view = new SearchView({ el: $("#search_container") });</script><script type="text/template" id="search_template">    <!-- Access template variables with <%= %> -->    <label><%= search_label %></label>    <input type="text" id="search_input" />    <input type="button" id="search_button" value="Search" /></script>

?

上面的代码说明一下:

render方法就是渲染页面的方法;View层的事件绑定也支持了:
"click input[type=button]": "doSearch";对于模板的使用,先定义这个模板:
<script type="text/template" id="search_template">……</script>
然后模板+数据来生成结果:
var template = _.template( $("#search_template").html(), variables );
然后再把结果渲染到画布上:
this.el.html( template );

Model

?

Model是JavaScript应用的核心,在这里它包括了包含大量逻辑的数据交互、转换、校验,属性的计算和访问控制:

?

Person = Backbone.Model.extend({        defaults: {            name: 'Fetus',            age: 0,            children: []        },        initialize: function(){            alert("Welcome to this world");        },        adopt: function( newChildsName ){            var children_array = this.get("children");            children_array.push( newChildsName );            this.set({ children: children_array });        }    });        var person = new Person({ name: "Thomas", age: 67, children: ['Ryan']});    person.adopt('John Resig');    var children = person.get("children"); // ['Ryan', 'John Resig']

?

简单说明一下:

default是用来定义Model的属性的默认取值的;设值(setter)可以这样写:
set({ children: children_array });而取值(getter)则这样写:
person.get("children")。

再来看看事件绑定的写法(看下面的bind方法的调用)和属性校验的写法(validate方法):

?

    Person = Backbone.Model.extend({        // If you return a string from the validate function,        // Backbone will throw an error        validate: function( attributes ){            if( attributes.age < 0 && attributes.name != "Dr Manhatten" ){                return "You can't be negative years old";            }        },        initialize: function(){            alert("Welcome to this world");            this.bind("error", function(model, error){                // We have received an error, log it, alert it or forget it :)                alert( error );            });        }    });

?

Router

?

Router以前是被backbone称为Controller的,它使用URL的hash来做地址映射。主要的写法有“*”和“:”两种:

?

    var AppRouter = Backbone.Router.extend({        routes: {            "/posts/:id/:action": "getPost",            "*actions": "defaultRoute" // Backbone will try match the route above first        },        getPost: function( id, action ) {            // Note the variable in the route definition being passed in here            alert( "Get post number " + id );           },        defaultRoute: function( actions ){            alert( actions );         }    });    // Instantiate the router    var app_router = new AppRouter;    // Start Backbone history a neccesary step for bookmarkable URL's    Backbone.history.start();

?

稍微说明一下:

如果URL为http://example.com/#/posts/121/delete的话,那么:
"/posts/:id/:action"匹配上了,那么id="121",action="delete"这样的参数传到getPost方法里;
如果没匹配上,"121/delete"将作为参数传到defaultRoute方法里。在创建好所有的router之后,一定要调用一下Backbone.history.start()方法来route你的URL。

?

Collection

?

Collection其实就是一组Model的有序集合。

?

    var Song = Backbone.Model.extend({        defaults: {            name: "Not specified",            artist: "Not specified"        },        initialize: function(){            console.log("Music is the answer");        }    });        var Album = Backbone.Collection.extend({        model: Song    });        var song1 = new Song({ name: "How Bizarre", artist: "OMC" });    var song2 = new Song({ name: "Sexual Healing", artist: "Marvin Gaye" });    var song3 = new Song({ name: "Talk It Over In Bed", artist: "OMC" });        var myAlbum = new Album([ song1, song2, song3]);    console.log( myAlbum.models ); // [song1, song2, song3]    

?

说明一下:

对象集合怎么放进去(比如数组形式),它就怎么管理:
var myAlbum = new Album([ song1, song2, song3]);

文章系本人原创,转载请注明作者和出处

?

1 楼 有女未长成 2012-05-14   没个示例下载吗???
期待中 2 楼 RayChase 2012-05-14   有女未长成 写道没个示例下载吗???
期待中
文章的第一句话的链接里面有。
http://backbonetutorials.com/examples/modular-backbone/ 3 楼 有女未长成 2012-05-23   RayChase 写道有女未长成 写道没个示例下载吗???
期待中
文章的第一句话的链接里面有。
http://backbonetutorials.com/examples/modular-backbone/
谢谢,第一句里面的前两个链接都点过,鬼使神差的就这个链接没点……

热点排行