BackboneJS .sync()方法
Backbone每次調用讀或模型保存到服務器的功能。它代示模型的狀態。
語法
sync.(method, model, options)
參數:
- method: 它代表了CRUD操作,如創建,讀取,更新和刪除。
- model: 包括要保存的模型。
- options: 觸發成功還是錯誤消息取決於方法成功。
示例
<!DOCTYPE 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:"gitbook.net", title:"專注於IT教學的網站..." }); //The myval.fetch() method displays the model's state by delegating to sync() method myval.fetch(); </script> </body> </html>
輸出
讓我們進行以下步驟來看看上麵的代碼工作:
-
保存以上代碼到sync.html文件
-
在瀏覽器打開這個HTML文件。