BackboneJS - 同步 Backbone.sync



說明

這是 Backbone 每當讀取或儲存模型到伺服器時呼叫的函式。它表示模型的狀態。

語法

sync.(method, model, options)

引數

  • method − 它表示 CRUD 操作,例如建立、讀取、更新和刪除。

  • model − 它包括要儲存的模型。

  • options − 它根據方法的成功觸發成功或錯誤訊息。

示例

<!DOCTYPE html>
<html>
   <head>
      <title>Sync 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 fetched 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));
         };

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

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

輸出

讓我們執行以下步驟,瞭解上述程式碼如何工作 −

  • 將以上程式碼儲存在 backbone-sync.htm 檔案中。

  • 在瀏覽器中開啟此 HTML 檔案。

backbonejs_sync.htm
廣告
© . All rights reserved.