Created
December 25, 2012 00:30
-
-
Save simple10/4371158 to your computer and use it in GitHub Desktop.
Backbone meta data plugin
This file contains 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
# | |
# Add meta data support to Model and Collection | |
# Allows server to include additional meta data that gets automatically parsed and stashed in [model|collection].meta | |
# | |
# Usage: | |
# Include this file after backbone.js | |
# Set data_key on Model or Collection | |
# | |
# If data_key is not set, original parse method will be invoked. | |
# | |
# Example Collection: | |
# | |
# Server response ... | |
# { | |
# "response_time": 148, | |
# "next_page_token": 'abk382', | |
# "items": [ | |
# { | |
# "id": "abc123", | |
# "title": "Thing 1" | |
# }, | |
# { | |
# "id": "def456", | |
# "title": "Thing 2" | |
# } | |
# ] | |
# } | |
# | |
# MyCollection extends Backbone.Collection | |
# data_key: 'items' | |
# | |
# | |
_extended = | |
# Set to name of key that contains Model or Collection data in server results | |
data_key: null | |
# Parse out meta data from server results and set @meta | |
parseMeta: (resp) -> | |
@meta = {} | |
for key, val of resp | |
@meta[key] = val | |
delete @meta[@data_key] | |
# Override Backbone's parse method | |
parse: (resp, xhr) -> | |
if @data_key && resp && resp[@data_key] | |
@parseMeta(resp) | |
resp = resp[@data_key] | |
@_original_parse_without_meta(resp, xhr) | |
# Keep reference to original parse method | |
Backbone.Model.prototype._original_parse_without_meta = Backbone.Model.prototype.parse | |
Backbone.Collection.prototype._original_parse_without_meta = Backbone.Collection.prototype.parse | |
_.extend(Backbone.Model.prototype, _extended) | |
_.extend(Backbone.Collection.prototype, _extended) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment