Last active
May 29, 2017 10:13
-
-
Save lqt0223/cfc4fabeb1685df38a92d5bfe5afffe5 to your computer and use it in GitHub Desktop.
The difference between 'sync' event and 'sync' attribute in Backbone
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html lang="en"> | |
<head> | |
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script> | |
<script src="https://cdn.bootcss.com/underscore.js/1.8.3/underscore.js"></script> | |
<script src="https://cdn.bootcss.com/backbone.js/1.3.3/backbone.js"></script> | |
</head> | |
<body> | |
<script> | |
// The difference between 'sync' event and 'sync' attribute in Backbone | |
var HOST = 'https://jsonplaceholder.typicode.com' | |
var PostModel = Backbone.Model.extend({}) | |
var BaseCollection = Backbone.Collection.extend({ | |
// The attribute 'sync' defines the behavior when collection or model start syncing data | |
// (usually the syncing operation is fired by fetch()) | |
// When this function is invoked before http request completion | |
// Override this to perform a custom sync operation | |
sync: function(method, collection, options) { | |
// params: | |
// method: one of the CRUD method "create / read / update / delete" | |
// collection: the collection object | |
// options: the option object passed in when invoking fetch() | |
// do some custom operations... | |
console.log(method, collection, options, "sync attribute"); | |
// but remember to invoke the backbone default sync if still needed | |
Backbone.Collection.prototype.sync.apply(this, arguments) | |
}, | |
initialize: function(){ | |
var resourceName = this.resourceName | |
this.url = HOST + '/' + resourceName | |
// The 'sync' event is fired when new data is successfully fetched, | |
// and collection or model has finished updating the data | |
this.listenTo(this, "sync", (collection,response,options) => { | |
// params: | |
// collection: the collection object | |
// response: server response in JSON object form | |
// options: the option object passed in when invoking fetch() | |
console.log(collection,response,options, "sync event"); | |
}) | |
}, | |
}) | |
var PostCollection = BaseCollection.extend({ | |
model: PostModel, | |
resourceName: 'posts', | |
}) | |
var postCollection = new PostCollection() | |
postCollection.fetch({ | |
testOption: "test" | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment