Skip to content

Instantly share code, notes, and snippets.

@victor-github
Created May 24, 2011 16:25
Show Gist options
  • Save victor-github/989056 to your computer and use it in GitHub Desktop.
Save victor-github/989056 to your computer and use it in GitHub Desktop.
Convenience methods for Backbone.js
//gets value if field exists, and returns empty string otherwise
Backbone.Model.prototype.getValue = function(field) {
if (this.attributes[field] != undefined) {
return this.attributes[field];
}
else {
return '';
}
};
//return an array composed of the values of 'field' for each of the models in the collection; useful for e.g. autocomplete
Backbone.Collection.prototype.toArray = function(field) {
var array = [];
for (var i = 0; i <= this.size()-1; i++) {
array.push(this.models[i].get(field));
}
return array;
};
@tirams
Copy link

tirams commented May 3, 2012

// FYI this gives you the second function
collection.pluck("fieldName");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment