它通過委派sync() 方法讀取和每次儲存模型時呼叫Backbone便會儲存模型的資料。
model.save(attributes,options)
<!DOCTYPE html> <head> <title> Model 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> <script type="text/javascript"> var details = new Backbone.Model({ name: "Hi..", site: "Welcome to YiiBai" }); Backbone.sync = function(method, model) { document.write(method + ": " + model.get('name')+ " " +model.get('site')); model.set('id', 1); }; details.save(); document.write("<br>"); details.save({name : "Hello World!!!"}); </script> </head> <body></body> </html>
讓我們進行以下步驟來看看上面的程式碼工作:
儲存上述程式碼在檔案save.html
開啟瀏覽器這個HTML檔案。