前端編程提高之旅(四)----backbone初體驗
來源:程序員人生 發布時間:2014-09-05 22:04:42 閱讀次數:3564次
來到新的實習單位,公司的業務模式、組織架構、開發技術、開發規范對于樂帝這樣的職場菜鳥來說都是新的,這一周入職的這幾天主要在熟悉公司采用的前端架構,前端架構基本包括:backbone、marionette、requirejs。由于樂帝在愛奇藝實習期間,自學了PHP技術,對smarty模板及thinkphp框架有一個了解,接觸前端MVC還是有點基礎的。
公司有一套專業的前端培訓流程清單。這周主要的工作包括:閱讀backbone簡要文檔、讀backbone的todoMVC例子、通讀backbone官方文檔、再讀backbone的todoMVC例子、閱讀marionette簡要介紹、按照todoMVC源碼,手寫了一遍todoMVC代碼、閱讀backbone總結文章,總算大體弄清楚了backbone的來龍去脈。
回頭來看,對于提升學習效率最高的方法是:閱讀簡單概念的介紹并配合例子、看一個比較綜合的例子對簡單概念做吸收、閱讀官方文檔所有API、敲一遍綜合例子做吸收。這樣的學習順序遵循了認識、實踐的原則。樂帝基本上按照這樣的順序學習了backbone。下面代碼段的注釋是樂帝從整體對model、collection、view的理解。
$(function(){
var Todo = Backbone.Model.extend({
default:function(){
return {
title:"hello ledi",
order: Todos.nextOrder(),
done:false
};
},
toggle:function(){
return this.save(done,!this.get("done"));
}
});//構造基本的數據模型及對數據的處理
TodoList = Backbone.Collection.extend({
model:Todo,
localStorage: new Backbone.LocalStorage("todos-backbone"),
done:function(){
return this.where({done:true});
},
remaining:function(){
return this.where({done:false});
},
nextOrder:function(){
if(!this.length)
{
return 1;
}
else{
return this.last().get('order')+1;
}
},
comparator:'order'
});//作為數據模型的集合,對模型進行增刪查找、排序等管理
var Todos =new TodoList;
var TodoView = Backbone.View.extend({
tagName:"li",
template: _.template($('#item-template').html()),
events: {
"click .toggle" : "toggleDone",
"dblclick .view" : "edit",
"click a.destroy" : "clear",
"keypress .edit" : "updateOnEnter",
"blur .edit" : "close"
},//事件定義,控制交互部分
initialize:function(){
this.listenTo(this.model,'change',this.render);
this.listenTo(this.model,'destroy',this.remove);
},// 通過監聽與model數據實現綁定
render:function(){
this.$el.html(this.template(this.model.toJSON()));
this.$el.toggleClass('done', this.model.get('done'));//切換是否有done類,調試查看此類
this.input = this.$('.edit');
return this;
},//初始化渲染模板內容,作為顯示部分
toggleDone:function(){
this.model.toggle();
},
edit:function(){
this.$el.addClass(".editing");
this.input.focus();
},
close:function(){
var value = this.input.val();
if(!value)
{
this.clear();
}
else{
this.model.save({title:value});
this.$el.removeClass(".editing");
}
},
updateOnEnter:function(e){
if(e.keyCode == 13)
{
this.close();
}
},
clear:function(){
this.model.destroy();
}
});//todoview與model一一對應,對model數據進行顯示及交互操作
var appView = Backbone.View.extend({
el: $("#todoapp"),
statsTemplate: _.template($('#stats-template').html()),// 統計模板
events: {
"keypress #new-todo": "createOnEnter",
"click #clear-completed": "clearCompleted",
"click #toggle-all": "toggleAllComplete"
},// 監聽事件
initialize:function(){
this.input = this.$("#new-todo");
this.allCheckbox = this.$("#toggle-all")[0];
this.listenTo(Todos, 'add', this.addOne);
this.listenTo(Todos, 'reset', this.addAll);
this.listenTo(Todos, 'all', this.render);
this.footer = this.$('footer');
this.main = $('#main');
Todos.fetch();
},//監聽collection的變化,實現與collection的綁定
render:function(){
var done = Todos.done().length;
var remaining = Todos.remaining().length;
if(!Todo.length){
this.main.show();
this.footer.show();
this.footer.html(this.statsTemplate({done: done, remaining: remaining}));
}
else{
this.main.hide();
this.footer.hide();
}
this.allCheckbox.checked = !remaining;
},// 實現整體顯示
addOne:function(todo){
view = new TodoView({model:todo});
this.$("#todo-list").append(view.render().el);
},
addAll:function(){
Todos.each(this.addOne,this);//這里用到collection和model溝通了
},
createOnEnter:function(e){
if(e.keyCode!=13) return;
if(!this.input.val()) return;
Todos.create({title:this.input.val()});
this.input.val('');
},
clearCompleted:function(){
_.invoke(Todos.done,'destroy');
return false;
},
toggleAllComplete:function(){
var done = this.allCheckbox.checked;
Todos.each(function(todo){todo.save(done,'done');});
}
});//作為全局的view,控制多個todoview顯示交互及其他顯示模塊的交互部分
var app = new appView;
})//view基本模式:通過初始化及渲染函數進行最初顯示,并通過定義事件列表,編寫對應執行函數,實現交互
以上例子是樂帝研究的todo例子,并動手敲了一遍,對各個模塊功能的理解。model提供數據模型及對數據處理;collection則是model的集合,主要以model為處理對象,對其增刪查找、排序等各種操作;view則是傳統后端MVC架構中的起Controller功能,主要負責控制顯示、交互邏輯。
backbone簡要文檔對view的論述并沒有后來讀的文章寫得清楚,這里樂帝給出介紹view及模板的典型例子,用于理解view作為MVC核心地位的職能;
<!-- Templates -->
<script type="text/template" id="hello-template">
<div>
<h3 id="hello"><%= message %></h3>
<button id="toggle">Toggle</button>
</div>
</script>
<!-- underscore自帶模板引擎,通過<%= var %>接收傳入的變量 -->
<script type="text/javascript">
var TestView = Backbone.View.extend({
events: {
'click button#toggle' : 'toggle'
},
initialize: function() {
this.template = _.template($("#hello-template").html()); // 設定模板
this.render();
},
render: function() {
this.$el.html(this.template({message: "hello world!"})); // 渲染模板
return this;
},
toggle: function() {
this.$("#hello").toggle();
return this;
}
});
$(function () {
var v = new TestView({el: $('#hello')});
});
//這個例子中,給出了設置模板、傳入參數、渲染頁面、添加交互事件的方法,對于理解view功能:顯示頁面、添加交互,非常有幫助。
//http://blog.csdn.net/raptor/article/details/8566017
</script>
這段代碼給出的顯示和交互非常簡單,麻雀雖小、五臟俱全。能非常清楚的看到view用于顯示頁面和添加交互所要做的事情。接下來則是model和collection的例子:
var Foo = Backbone.Model.extend({});
// 或是初始化默認數據
var Foo = Backbone.Model.extend({
defaults: {
name: "hello",
value: "233"
}
});
// 或是運行時賦值。
// 比如這樣:
var foo = new Foo({name:"world", value:"874"});
// 或這樣:
var foo = new Foo;
foo.set({name:"world", value:"874"});
var FooList = Backbone.Collection.extend({
model: Foo
});
var foos = new FooList;
foos.add([{name:"hello", value:"233"},{name:"world", value:"874"}]);
$(function () {
$("#hello").text(JSON.stringify(foos.at(0))); ;
});
這段代碼給出了model及collection基本定義和使用,除此之外還會涉及增刪查找、有效性驗證、事件綁定等功能。由于都會涉及到后端的交互,這里樂帝涉獵不多,詳情可戳我。
至于router則是定義路由規則,相對簡單。樂帝下一步則是需要在這個基礎上使用requirejs組織todoMVC代碼以及閱讀marionette使用其寫一個todoMVC例子,并最終在talentjs上寫MVC例子,真正的上手項目。
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈