Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
127
rated 0 times [  132] [ 5]  / answers: 1 / hits: 15402  / 13 Years ago, wed, january 25, 2012, 12:00:00

What is options in Backbone.js that I see all over the official source code and also used in a tutorial blog by Thomas Davis with sample code here:



Friends = Backbone.Collection.extend({
initialize: function (models, options) {
this.bind(add, options.view.addFriendLi);
}
});


I don't see any other tutorials using it, and even the doc mentioning it. It does, but in a context kind of format ([options]), not in a hard-coded options: options.view.addFriendLi


More From » backbone.js

 Answers
8

options, conventionally, is a javascript object of key/value pairs that provide data/context/arguments/configuration to a method call. Think of it like named arguments, as opposed to ordered arguments.



For example:



var makePerson = function(name, options) {
var person = {};
person.name = name;
person.age = options.age;
return person;
};

var me = makePerson('Alex', {age:30}); // In 3 days... scary :(


How the function being called uses this object, is up to that function.



The documentation for backbone for Collection.initialize() does not seem to list what keys on the options object are used or expected, which is unfortunate. So without looking at the source, there is no way to tell. But your example does seem to indicate a view key is expected. So you might call it like this:



var friendsCollection = new Friends(userModels, {view: someBackboneView});


This is simply a convention many libraries tend to use, and there is nothing special about it. But usually many keys in an object that is passed to a function call is better than a funciton that you call with many arguments, because each value has a label which makes it clear what each value is for.






Looking a bit further, now here: http://documentcloud.github.com/backbone/docs/backbone.html#section-53



It looks like Collection.initialize() only accepts a single key in it's options: comparator. Here you can define a function used to sort the models in the collection:
http://documentcloud.github.com/backbone/#Collection-comparator



Working that into your example, you would call that like this:



var friendsCollection = new Friends(userModels, {
view: someBackboneView,
comparator: function(friend) {
return friend.get('age');
}
});

[#87818] Monday, January 23, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
parisc

Total Points: 438
Total Questions: 119
Total Answers: 119

Location: Turkmenistan
Member since Sat, Apr 16, 2022
2 Years ago
;