BackboneJS collection.sync()方法


使用Backbone.sync持久化一個集合的狀態到伺服器。

語法

collection.sync(method, collection, options)

引數:

  • method: 表示CRUD操作,如建立,讀取,更新和刪除。
  • collection: 包含設定模型來儲存資料的收集。
  • options: 激發成功或錯誤訊息取決於方法成功。

範例

<!DOCTYPE html>
   <head>
      <title>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">
      	 //The sync() method reads and fetches the model data
         Backbone.sync = function(method, model) {
            document.write("The state of the model is:");
            document.write("<br>");

            //The 'method' specifies state of the model
            document.write(method + ": " + JSON.stringify(model));
         };

         //The 'myval' is collection instance and contains the values which are to be fetched in the collection
         var myval = new Backbone.Collection({
            site:"YiiBai",
            title:"Simply Easy Learning..."
         });

         //The myval.fetch() method display the model's state by delegating the sync() method
         myval.fetch();
      </script>
   </body>
</html>

輸出

讓我們進行以下步驟來看看上面的程式碼工作:

  • 儲存上述程式碼在檔案sync.html

  • 在瀏覽器開啟這個HTML檔案。