欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Backbone.js框架中Model與Collection的使用實(shí)例

 更新時(shí)間:2016年05月07日 11:56:37   投稿:goldensun  
這篇文章主要介紹了Backbone.js框架中Model與Collection的使用實(shí)例,Collection是Model的一個(gè)有序的集合,需要的朋友可以參考下

Model
關(guān)于backbone,最基礎(chǔ)的一個(gè)東西就是model,這個(gè)東西就像是后端開發(fā)中的數(shù)據(jù)庫映射那個(gè)model一樣,也是數(shù)據(jù)對(duì)象的模型,并且應(yīng)該是和后端的model有相同的屬性(僅是需要通過前端來操作的屬性)。
下面就從實(shí)例來一步一步的帶大家來了解backbone的model到底是什么樣的一個(gè)東西。
首先定義一個(gè)html的頁面:

<!DOCTYPE html>
<html>
<head>
<title>the5fire-backbone-model</title>
</head>
<body>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
<script>
(function ($) {
/**
 *此處填充代碼
 **/
})(jQuery);
</script>
</html>

下面的代碼需要填到這個(gè)html的script標(biāo)簽中的function中。

1、最簡單的一個(gè)對(duì)象

Man = Backbone.Model.extend({
    initialize: function(){
      alert('Hey, you create me!');
    }
  });
var man = new Man;

這個(gè)就很簡單了,在helloworld里面也有了一個(gè)model的展現(xiàn),不定義了屬性,這里是一個(gè) 初始化時(shí)的方法,或者稱之為構(gòu)造函數(shù)。​​

2、對(duì)象賦值的兩種方法
第一種,直接定義,設(shè)置默認(rèn)值。

Man = Backbone.Model.extend({
  initialize: function(){
    alert('Hey, you create me!');
  },
  defaults: {
    name:'張三',
    age: '38'
  }
});

var man = new Man;
alert(man.get('name'));

第二種,賦值時(shí)定義

Man = Backbone.Model.extend({
  initialize: function(){
    alert('Hey, you create me!');
  }
});
man.set({name:'the5fire',age:'10'});
alert(man.get('name'));

取值的時(shí)候都是用get。

3、對(duì)象中的方法

Man = Backbone.Model.extend({
  initialize: function(){
    alert('Hey, you create me!');
  },
  defaults: {
    name:'張三',
    age: '38'
  },
  aboutMe: function(){
    return '我叫' + this.get('name') + ',今年' + this.get('age') + '歲';
  }
});
var man = new Man;
alert(man.aboutMe());

4、監(jiān)聽對(duì)象中屬性的變化

Man = Backbone.Model.extend({
  initialize: function(){
    alert('Hey, you create me!');
    //初始化時(shí)綁定監(jiān)聽
    this.bind("change:name",function(){
      var name = this.get("name");
      alert("你改變了name屬性為:" + name);
    });
  },
  defaults: {
    name:'張三',
    age: '38'
  },
  aboutMe: function(){
    return '我叫' + this.get('name') + ',今年' + this.get('age') + '歲';
  }
});
var man = new Man;
man.set({name:'the5fire'}) //觸發(fā)綁定的change事件,alert。

5、為對(duì)象添加驗(yàn)證規(guī)則,以及錯(cuò)誤提示

Man = Backbone.Model.extend({
  initialize: function(){
    alert('Hey, you create me!');
    //初始化時(shí)綁定監(jiān)聽
    this.bind("change:name",function(){
      var name = this.get("name");
      alert("你改變了name屬性為:" + name);
    });
    this.bind("error",function(model,error){
      alert(error);
    });
  },
  defaults: {
    name:'張三',
    age: '38'
  },
  validate:function(attributes){
    if(attributes.name == '') {
      return "name不能為空!";
    }
  },
  aboutMe: function(){
    return '我叫' + this.get('name') + ',今年' + this.get('age') + '歲';
  }
});
var man = new Man;
man.set({name:''}); //根據(jù)驗(yàn)證規(guī)則,彈出錯(cuò)誤提示。

6、對(duì)象的獲取和保存,需要服務(wù)器端支持才能測試。
首先需要為對(duì)象定義一個(gè)url屬性,調(diào)用save方法時(shí)會(huì)post對(duì)象的所有屬性到server端。

Man = Backbone.Model.extend({
  url:'/save/',
  initialize: function(){
    alert('Hey, you create me!');
    //初始化時(shí)綁定監(jiān)聽
    this.bind("change:name",function(){
      var name = this.get("name");
      alert("你改變了name屬性為:" + name);
    });
    this.bind("error",function(model,error){
      alert(error);
    });
  },
  defaults: {
    name:'張三',
    age: '38'
  },
  validate:function(attributes){
    if(attributes.name == '') {
      return "name不能為空!";
    }
  },
  aboutMe: function(){
    return '我叫' + this.get('name') + ',今年' + this.get('age') + '歲';
  }
});
var man = new Man;;
man.set({name:'the5fire'});
man.save(); //會(huì)發(fā)送POST到模型對(duì)應(yīng)的url,數(shù)據(jù)格式為json{"name":"the5fire","age":38}
//然后接著就是從服務(wù)器端獲取數(shù)據(jù)使用方法fetch([options])
var man1 = new Man;
//第一種情況,如果直接使用fetch方法,那么他會(huì)發(fā)送get請(qǐng)求到你model的url中,
  //你在服務(wù)器端可以通過判斷是get還是post來進(jìn)行對(duì)應(yīng)的操作。
man1.fetch();
//第二種情況,在fetch中加入?yún)?shù),如下:
man1.fetch({url:'/getmans/'});
  //這樣,就會(huì)發(fā)送get請(qǐng)求到/getmans/這個(gè)url中,
  //服務(wù)器返回的結(jié)果樣式應(yīng)該是對(duì)應(yīng)的json格式數(shù)據(jù),同save時(shí)POST過去的格式。

//不過接受服務(wù)器端返回的數(shù)據(jù)方法是這樣的:
man1.fetch({url:'/getmans/',success:function(model,response){
    alert('success');
    //model為獲取到的數(shù)據(jù)
    alert(model.get('name'));
  },error:function(){
    //當(dāng)返回格式不正確或者是非json數(shù)據(jù)時(shí),會(huì)執(zhí)行此方法
    alert('error');
  }});

注:上述代碼僅僅均為可正常執(zhí)行的代碼,不過關(guān)于服務(wù)器端的實(shí)例在后面會(huì)有。
這里還要補(bǔ)充一點(diǎn),就是關(guān)于服務(wù)器的異步操作都是通過Backbone.sync這個(gè)方法來完成的,調(diào)用這個(gè)方法的時(shí)候會(huì)自動(dòng)的傳遞一個(gè)參數(shù)過去,根據(jù)參數(shù)向服務(wù)器端發(fā)送對(duì)應(yīng)的請(qǐng)求。比如你save,backbone會(huì)判斷你的這個(gè)對(duì)象是不是新的,如果是新創(chuàng)建的則參數(shù)為create,如果是已存在的對(duì)象只是進(jìn)行了改變,那么參數(shù)就為update,如果你調(diào)用fetch方法,那參數(shù)就是read,如果是destory,那么參數(shù)就是delete。也就是所謂的CRUD ("create", "read", "update", or "delete"),而這四種參數(shù)對(duì)應(yīng)的請(qǐng)求類型為POST,GET,PUT,DELETE。你可以在服務(wù)器根據(jù)這個(gè)request類型,來做出相應(yīng)的CRUD操作。

Note:
關(guān)于url和urlRoot的事,如果你設(shè)置了url,那么你的CRUD都會(huì)發(fā)送對(duì)應(yīng)請(qǐng)求到這個(gè)url上,但是這樣又一個(gè)問題,就是delete請(qǐng)求,發(fā)送了請(qǐng)求,但是卻沒有發(fā)送任何數(shù)據(jù),那么你在服務(wù)器端就不知道應(yīng)該刪除哪個(gè)對(duì)象(記錄),所以這里又一個(gè)urlRoot的概念,你設(shè)置了urlRoot之后,你發(fā)送PUT和DELETE請(qǐng)求的時(shí)候,其請(qǐng)求的url地址就是:/baseurl/[model.id],這樣你就可以在服務(wù)器端通過對(duì)url后面值的提取更新或者刪除對(duì)應(yīng)的對(duì)象(記錄)。

Collection
collection是model對(duì)象的一個(gè)有序的集合,概念理解起來十分簡單,在通過幾個(gè)例子來看一下,會(huì)覺得更簡單。
1、關(guān)于book和bookshelf的例子

Book = Backbone.Model.extend({

defaults : {  // 感謝網(wǎng)友藍(lán)色動(dòng)力指正改為defaults

title:'default'

},

initialize: function(){

//alert('Hey, you create me!');

}

});

BookShelf = Backbone.Collection.extend({

model : Book

});

var book1 = new Book({title : 'book1'});

var book2 = new Book({title : 'book2'});

var book3 = new Book({title : 'book3'});

//var bookShelf = new BookShelf([book1, book2, book3]); //注意這里面是數(shù)組,或者使用add

var bookShelf = new BookShelf;

bookShelf.add(book1);

bookShelf.add(book2);

bookShelf.add(book3);

bookShelf.remove(book3);



//基于underscore這個(gè)js庫,還可以使用each的方法獲取collection中的數(shù)據(jù)

bookShelf.each(function(book){

alert(book.get('title'));

});

很簡單,不解釋
2、使用fetch從服務(wù)器端獲取數(shù)據(jù)
首先要在上面的的Bookshelf中定義url,注意collection中并沒有urlRoot這個(gè)屬性?;蛘吣阒苯釉趂etch方法中定義url的值,如下:

bookShelf.fetch({url:'/getbooks/',success:function(collection,response){

collection.each(function(book){

alert(book.get('title'));

});

},error:function(){

alert('error');

}});

其中也定義了兩個(gè)接受返回值的方法,具體含義我想很容易理解,返回正確格式的數(shù)據(jù),就會(huì)調(diào)用success方法,錯(cuò)誤格式的數(shù)據(jù)就會(huì)調(diào)用error方法,當(dāng)然error方法也看添加和success方法一樣的形參。
對(duì)應(yīng)的BookShelf的返回格式如下:[{'title':'book1'},{'title':'book2'}.....]
3、reset方法
這個(gè)方法的時(shí)候是要和上面的fetch進(jìn)行配合的,collection在fetch到數(shù)據(jù)之后,會(huì)調(diào)用reset方法,所以你需要在collection中定義reset方法或者是綁定reset方法。這里使用綁定演示:

bookShelf.bind('reset',showAllBooks);

showAllBooks = function(){

bookShelf.each(function(book){

  ​//將book數(shù)據(jù)渲染到頁面。

});

}

綁定的步驟要在fetch之前進(jìn)行。
下面給出關(guān)于collection的完整代碼,需要服務(wù)器端支持才行,服務(wù)器端的搭建在后面會(huì)寫到。

<!DOCTYPE html>
<html>
<head>
  <title>the5fire-backbone-collection</title>
</head>
<body>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
<script>
(function ($) {
  //collection是一個(gè)簡單的models的有序集合
  //1、一個(gè)簡單的例子

  Book = Backbone.Model.extend({
    defaults : {  // 感謝網(wǎng)友藍(lán)色動(dòng)力指正改為defaults
      title:'default'
    },
    initialize: function(){
      //alert('Hey, you create me!');
    }
  });
  BookShelf = Backbone.Collection.extend({
    model : Book
  });

  var book1 = new Book({title : 'book1'});
  var book2 = new Book({title : 'book2'});
  var book3 = new Book({title : 'book3'});

  //var bookShelf = new BookShelf([book1, book2, book3]); //注意這里面是數(shù)組,或者使用add
  var bookShelf = new BookShelf;
  bookShelf.add(book1);
  bookShelf.add(book2);
  bookShelf.add(book3);
  bookShelf.remove(book3);
  /*
  for(var i=0; i<bookShelf.models.length; i++) {
    alert(bookShelf.models[i].get('title'));
  }
  */
  //基于underscore這個(gè)js庫,還可以使用each的方法獲取collection中的數(shù)據(jù)
  bookShelf.each(function(book){
    alert(book.get('title'));
  });

  //2、使用fetch從服務(wù)器端獲取數(shù)據(jù),使用reset渲染
  bookShelf.bind('reset', showAllBooks);
  bookShelf.fetch({url:'/getbooks/',success:function(collection,response){
    collection.each(function(book){
      alert(book.get('title'));
    });
  },error:function(){
    alert('error');
  }});
  showAllBooks = function(){
    bookShelf.each(function(book){
      ​//將book數(shù)據(jù)渲染到頁面。
    });
  }
  //上述代碼僅僅均為可正常執(zhí)行的代碼,不過關(guān)于服務(wù)器端的實(shí)例在后面會(huì)有。
})(jQuery);
</script>
</html>

相關(guān)文章

最新評(píng)論