當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Backbone.js collection.parse()用法及代碼示例

每當服務器返回模型數據時,就會調用 Backbone.js 解析方法。集合的數據通過傳遞響應對象返回,數據以 JSON 格式返回。

用法:

collection.parse(response, options) )

參數說明:

response:它指定集合的​​模型屬性數組。

options:如果設置為 true,則表示 JSON 格式的數據。

我們舉一個例子來演示解析方法。

看這個例子:

<!DOCTYPE html>
   <head>
      <title>Parse Collection Example</title>
         <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
         <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script>
         <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script>
   </head>
   <body>
      <script type="text/javascript">
         //'MyModel' is a model name and  extended using the Backbone.Model class
         var MyModel = Backbone.Model.extend();

         // The variable 'myData' contains the values which are need to be parsed in the collection
         var myData ={
            "values":[{
               "fname":"Saurav",
               "lname":"Ganguly",
               "country":"India"
            }]
         };

         //'MyCollection' is a collection name
         var MyCollection = Backbone.Collection.extend({
            model:MyModel,   //The model 'MyModel' is specified by overriding the 'model' property
            parse:function(response, options){
               document.write(JSON.stringify(response));
            }
         });

         //The collection instance 'myCollection' extracts the values of 'myData'only if parse is set to true
         var mycollection = new MyCollection(myData, { parse:true });
      </script>
   </body>
</html>

輸出:

將上述代碼保存在 parse.html 文件中,然後在新瀏覽器中打開此文件。

BackboneJS Parse Collection



相關用法


注:本文由純淨天空篩選整理自 Backbone.js collection.parse()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。