Backbone what is a collection
Triggers a "change" event if the server's state differs from the current attributes. Returns a jqXHR if validation is successful and false otherwise. The attributes hash as in set should contain the attributes you'd like to change — keys that aren't mentioned won't be altered — but, a complete representation of the resource will be sent to the server. As with set , you may pass individual keys and values instead of a hash. If the model has a validate method, and validation fails, the model will not be saved.
If instead, you'd only like the changed attributes to be sent to the server, call model. Calling save with new attributes will cause a "change" event immediately, a "request" event as the Ajax request begins to go to the server, and a "sync" event after the server has acknowledged the successful change.
In the following example, notice how our overridden version of Backbone. Returns a jqXHR object, or false if the model isNew. Accepts success and error callbacks in the options hash, which will be passed model, response, options. Triggers a "destroy" event on the model, which will bubble up through any collections that contain it, a "request" event as it begins the Ajax request to the server, and a "sync" event, after the server has successfully acknowledged the model's deletion.
Underscore Methods 9 Backbone proxies to Underscore. They aren't all documented here, but you can take a look at the Underscore documentation for the full details…. If the attributes are valid, don't return anything from validate ; if they are invalid return an error of your choosing. It can be as simple as a string error message to be displayed, or a complete error object that describes the error programmatically.
The validate method receives the model attributes as well as any options passed to set or save , if validate returns an error, save does not continue, the model attributes are not modified on the server, an "invalid" event is triggered, and the validationError property is set on the model with the value returned by this method.
The validate method receives the model attributes as well as any options passed to isValid , if validate returns an error an "invalid" event is triggered, and the error is set on the model in the validationError property. If your models are located somewhere else, override this method with the correct logic. Generates URLs of the form: "[collection. Delegates to Collection url to generate the URL, so make sure that you have it defined, or a urlRoot property, if all models of this class share a common root URL.
A model with an id of , stored in a Backbone. Note that urlRoot may also be a function. The function is passed the raw response object, and should return the attributes hash to be set on the model.
The default implementation is a no-op, simply passing through the JSON response. Override this if you need to work with a preexisting API, or better namespace your responses. If you're working with a Rails backend that has a version prior to 3. To disable this behavior for seamless Backbone integration, set:. If the model does not yet have an id , it is considered to be new. If an attribute is passed, returns true if that specific attribute has changed.
Note that this method, and the following change-related ones, are only useful during the course of a "change" event. Optionally, an external attributes hash can be passed in, returning the attributes in that hash which differ from the model. This can be used to figure out which portions of a view should be updated, or what calls need to be made to sync the changes to the server. Useful for getting a diff between versions of a model, or getting back to a valid state after an error occurs.
Collections are ordered sets of models. You can bind "change" events to be notified when any model in the collection has been modified, listen for "add" and "remove" events, fetch the collection from the server, and use a full suite of Underscore.
Any event that is triggered on a model in a collection will also be triggered on the collection directly, for convenience. This allows you to listen for changes to specific attributes in any model in a collection, for example: documents. Collection , providing instance properties , as well as optional classProperties to be attached directly to the collection's constructor function. If defined, you can pass raw attributes objects and arrays and options to add , create , and reset , and the attributes will be converted into a model of the proper type using the provided options, if any.
A collection can also contain polymorphic models by overriding this property with a constructor that returns a model. Useful for combining models from multiple tables with different idAttribute values into a single collection. By default returns the value of the attributes' idAttribute from the collection's model class or failing that, id.
If your collection uses a model factory and those models have an idAttribute other than id you must override this method. Collection [models], [options] For use with collections as ES classes. If you define a preinitialize method, it will be invoked when the Collection is first created and before any instantiation logic is run for the Collection. Collection [models], [options] When creating a Collection, you may choose to pass in the initial array of models. The collection's comparator may be included as an option.
Passing false as the comparator option will prevent sorting. If you define an initialize function, it will be invoked when the collection is created. There are a couple of options that, if provided, are attached to the collection directly: model and comparator. Pass null for models to create an empty Collection with options. Usually you'll want to use get , at , or the Underscore methods to access model objects, but occasionally a direct reference to the array is desired.
This can be used to serialize and persist the collection as a whole. Underscore Methods 46 Backbone proxies to Underscore. Most methods can take an object or string to support model-attribute-style predicates or a function that receives the model instance as an argument.
If a model property is defined, you may also pass raw attributes objects and options, and have them be vivified as instances of the model using the provided options. Returns the added or preexisting, if duplicate models. Note that adding the same model a model with the same id to a collection more than once is a no-op.
Each model can be a Model instance, an id string or a JS object, any value acceptable as the id argument of collection. The model's index before removal is available to listeners as options.
Use reset to replace a collection with a new list of models or attribute hashes , triggering a single "reset" event on completion, and without triggering any add or remove events on any models. Returns the newly-set models. For convenience, within a "reset" event, the list of any previous models is available as options.
Pass null for models to empty your Collection with options. Here's an example using reset to bootstrap a collection during initial page load, in a Rails application:. Calling collection. If a model in the list isn't yet in the collection it will be added; if the model is already in the collection its attributes will be merged; and if the collection contains any models that aren't present in the list, they'll be removed. All of the appropriate "add" , "remove" , and "change" events are fired as this happens.
Returns the touched models in the collection. Useful if your collection is sorted, and if your collection isn't sorted, at will still retrieve models in insertion order. When passed a negative index, it will retrieve the model from the back of the collection.
Takes the same options as add. Takes the same options as remove. If you define a comparator, it will be used to sort the collection any time a model is added. A comparator can be defined as a sortBy pass a function that takes a single argument , as a sort pass a comparator function that expects two arguments , or as a string indicating the attribute to sort by.
Note that Backbone depends on the arity of your comparator function to determine between the two styles, so be careful if your comparator function is bound. Note how even though all of the chapters in this example are added backwards, they come out in the proper order:. Collections with a comparator will not automatically re-sort if you later change model attributes, so you may wish to call sort after changing model attributes that would affect the order.
Note that a collection with a comparator will sort itself automatically whenever a model is added. Calling sort triggers a "sort" event on the collection. Equivalent to calling map and returning a single attribute from the iterator. Useful for simple cases of filter. If no model matches returns undefined. Models within the collection will use url to construct URLs of their own. The function is passed the raw response object, and should return the array of model attributes to be added to the collection.
The options hash takes success and error callbacks which will both be passed collection, response, options as arguments. Delegates to Backbone. The server handler for fetch requests should return a JSON array of models. The behavior of fetch can be customized by using the available set options. For example, to fetch a collection, getting an "add" event for every new model, and a "change" event for every changed existing model, without removing anything: collection. Note that fetch should not be used to populate collections on page load — all models needed at load time should already be bootstrapped in to place.
Equivalent to instantiating a model with a hash of attributes, saving the model to the server, and adding the model to the set after being successfully created. Returns the new model. If client-side validation failed, the model will be unsaved, with validation errors. In order for this to work, you should set the model property of the collection. The create method can accept either an attributes hash and options to be passed down during model instantiation or an existing, unsaved model object.
Creating a model will cause an immediate "add" event to be triggered on the collection, a "request" event as the new model is sent to the server, as well as a "sync" event, once the server has responded with the successful creation of the model.
Collection and any collections which extend it. This can be used to add generic methods e. Web applications often provide linkable, bookmarkable, shareable URLs for important locations in the app.
Router provides methods for routing client-side pages, and connecting them to actions and events. For browsers which don't yet support the History API, the Router handles graceful fallback and transparent translation to the fragment version of the URL.
During page load, after your application has finished creating all of its routers, be sure to call Backbone. Define action functions that are triggered when certain URL fragments are matched, and provide a routes hash that pairs routes to actions. Note that you'll want to avoid using a leading slash in your route definitions:. Trailing slashes are treated as part of the URL, and correctly treated as a unique route when accessed. When the visitor presses the back button, or enters a URL, and a particular route is matched, the name of the action will be fired as an event , so that other objects can listen to the router, and be notified.
Router [options] For use with routers as ES classes. If you define a preinitialize method, it will be invoked when the Router is first created and before any instantiation logic is run for the Router. All options will also be passed to your initialize function, if defined.
Each matching capture from the route or regular expression will be passed as an argument to the callback. The name argument will be triggered as a "route:name" event whenever the route is matched. If the callback argument is omitted router[name] will be used instead. Routes added later may override previously declared routes. If you also wish to call the route function, set the trigger option to true.
In your simple solved example this pattern is visible pretty clear. Add a comment. Active Oldest Votes. Improve this answer.
Rob Hruska Rob Hruska k 28 28 gold badges silver badges bronze badges. I'm not sure that approach will work - you simply can't set an extension of Backbone. Collection i. Tracks as the model of another collection. You'll still want to keep Track as your Playlist. I have updated the code in the question. I didn't set a collection as the model of another collection. I set the colelction Tracks as an attribute of the model Playlist extends model.
Or am I wrong? Collections are ordered sets of Models. We just need to extend the backbone's collection class to create our own collection. Any event that is triggered on a model in a collection will also be triggered on the collection directly. This allows you to listen for changes to specific attributes in any model in a collection. When a model instance is created, it is invoked by defining the initialize function when the collection is created.
It looks at the model, whether or not it is already in the collection. If it isn't then it will be added to the collection. The merging of attributes is done only if that model is already in the collection. Collection holds model instances, we can define a Collection by extending the Backbone. Model attribute to specify the model instance.
Explaining the entire collection is beyond the scope of this article, for more information you can look at the Backbone. Stay in touch with the loop of this article series, there are many more features of Backbone.
View All. Working with Backbone. Collection : Part 6. Shridhar Sharma Updated date Jan 14, JS: Part 1 Model in Backbone. JS View : Part 5 Backbone. Collections Collections hold instances of models, in other words an ordered set of models that provide various types of methods for various operations.
0コメント