BackboneJS - Collection Sync
描述
它使用 Backbone.sync 将集合的状态持久化到服务器。
语法
collection.sync(method, collection, options)
参数
method − 它表示 CRUD 操作,例如创建、读取、更新和删除。
collection − 它包含一组模型来保存集合中的数据。
options − 根据成功的方法触发成功或错误消息。
示例
<!DOCTYPE html> <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"> //sync() 方法读取并获取模型数据 Backbone.sync = function(method, model) { document.write("模型的状态为:"); document.write("<br>"); //'method' 指定模型的状态 document.write(method + ": " + JSON.stringify(model)); }; //'myval' 是集合实例,包含要获取的值 //在集合中 var myval = new Backbone.Collection ({ site:"TutorialsPoint", title:"Simply Easy Learning..." }); //myval.fetch() 方法通过委托 sync() 方法来显示模型的状态 myval.fetch(); </script> </body> </html>
输出
让我们执行以下步骤来查看上述代码的工作原理 −
将上述代码保存在 sync.html 文件中。
在浏览器中打开此 HTML 文件。