ArticleDirectory
- Bind
- Unbind
- Trigger
- Extend
- Constructor/initialize
- Get
- Set
- Escapte
- Has
- Clear
- ID
- CID
- Attributes
- Ults
- Tojson
- Fetch
- Save
- Destroy
- Validate
- URL
- Urlroot
- Parse
- Clone
- Isnew
- Change
- Haschanged
- Changeattributes
- Previous
- Previusattributes
Backbone is a great JavaScript MVC Framework. using it to develop Web applications enables your clientCodeLess, fresher, easier to maintain, and more handsome. The following is a translation of the official documents.
The translation is incomplete, and it is not especially loyal to the original text. Because my English is very poor, I translated it according to my own understanding. If there is no pressure on English, I should try my best to see the original English text, or help me translate. Thank you.
Backbone is used to develop JavaScript applicationsProgramProvides a set of architecture, including key-value pairs (attributes) and custom eventsModelWith a wide range of enumeration APIs (annotation: dependent on the underscore set Operation)CollectionsAndViewAnd connect these to an existing restful JSON interface.
This project is hosted on GitHub and has annotated code, as well as online test kits, examples, and series guides.
You can submit bugs or discuss features on the GitHub issue page.# DocumentcloudChannel for IRC communication, raise a question in Google group, and send Twitter to @ documentcloud
Backbone is an open-source component of documentcloud.
Download and dependency
All source code and comments of the 41kb development version
Production Environment version 4.6 K packaged and gzip compressed
The only hard dependency of backone is underscore. js. To enable backbone. route to support restfull persistence and history and allow backbone. View to operate the Dom, json2.js and jquery or zepto must be included.
0.50 + updates
We take this opportunity to clarify some names in version 0.5.0.ControllerNowRouter,RefreshNowReset, PreviousSavelocationAndSetlocationFunction.NavigateReplaced,Backbone. syncSupported MethodsJquery. AjaxIf you want to usePushstateFeature, must be calledHistory. Start
Introduction
When developing Web applications, a large amount of JavaScript is involved. The first thing you need to learn is to prevent data from being written directly on the Dom. With jquery selector and callback, you can easily create a web application, operate the DOM directly, and easily synchronize data with the server database. However, developing a rich client application requires a more systematic approach.
In backbone, models represents your data, which can be created, verified, destroyed, and saved to the server. Every time the UI action triggers a property change of the model, the model will triggerChangeTime, allViewsYou can present the data of the model you contain when you receive the event, or re-present the data. You don't need to write glue code to search for DOM elements by ID, and manually update HTML-when the model changes, you only need to update the view.
The following examples can be run. Click "play" to execute them. You cannot click here to go to the original page)
Backbone. Events
EventsIs a module that can be attached to any object. It enables the object to bind and trigger custom naming events. Events does not need to be defined before binding, and parameters can be passed, as shown below.
VaRObject = {};
_. Extend (object, backbone. events );
Object. BIND ("alert ",Function(MSG ){
Alert ("triggered" + MSG );
});
Object. Trigger ("alert", "an event ");
Bind
Object. BIND (event, callback, [Context])
BindCallback, Callback willEventIf you have a large number of events on a page, you can use colons to separate namespaces, suchPoll: StartOrChange: Selection
To provide a context for the callback call, you can provide the third parameter, suchModel. BIND ('change', this. Render, this)
If a callback is bound toAllWhen an event occurs, it is called, and the first parameter of the callback is the event name. In the following example, all events of an object are represented to another object.
Proxy. BIND ("all ",Function(Eventname ){
Object. Trigger (eventname );
});
Unbind
Object. Unbind ([event], [callback])
Remove the event processing callback bound to an object. If callback is not specified, all callbacks of the specified event are removed. If the event is not specified, all events of the object are removed.
Object. Unbind ("change", onchange );//Removes just the onchange callback.
Object. Unbind ("change ");//Removes all "change" callbacks.
Object. Unbind ();//Removes all callbacks on object.
Trigger
Object. Trigger (event ,[ARGs]) *
When the callbacks of a given event is triggered, the specified ARGs is passed to callbacks.
Backbone. Model
ModelsIs the core of any JavaScript program. It includes Interactive Data of the program and a majority of data-related logic, such as type conversion, verification, calculation attributes, and access control. You can expand backbone. Model to add methods and attributes of the domain model, and provide a basic change (such as crud) function.
The following is an example. It defines a model, adds a custom method, sets properties, and binds a specific property change event (Change: color ). If you run the following code, the browser Sidebar will change to the color you entered. For more information, see the original article address)
VaRSidebar = backbone. model. Extend ({
Promptcolor:Function(){
VaRCsscolor = prompt ("Please enter a CSS color :");
This. Set ({color: csscolor });
}
});
Window. Sidebar =NewSidebar;
Sidebar. BIND ('change: color ',Function(Model, color ){
Certificate ('inclusidebar'0000.css ({Background: Color });
});
Sidebar. Set ({color: 'white '});
Sidebar. promptcolor ();
Extend
Backbone. model. Extend (properties, [classproperties])
Create your ownModel, You need extend a backbone. Model and provide instance attributesPropertiesYou can also use the OptionalClasspropertiesDirectly attached to the constructor. You have never used classproperties)
ExtendYou can correctly set the Javascript prototype chain. You can continue extend. The defined model automatically inherits the members of the parent class and overwrites the members of the parent class in the subclass, implement the custom logic of sub-classes.
VaRNote = backbone. model. Extend ({
Initialize:Function(){...},
Author:Function(){...},
Coordinates:Function(){...},
Allowedtoedit:Function(Account ){
Return True;
}
});
VaRPrivatenote = Note. Extend ({
Allowedtoedit:Function(Account ){
ReturnAccount. Owns (This);
}
});
JavaScript does not provide a simple method to call the parent class-it is a function with the same name on the High-Level JavaScript prototype chain. If your own model overwrites the default method of backbone. model, as shown inSet,SaveAnd you want to call the implementation of the parent class, you must call it explicitly, as shown below:
VaRNote = backbone. model. Extend ({
Set:Function(Attributes, options ){
Backbone. model. Prototype. Set. Call (This, Attributes, options );
...
}
});
Constructor/initialize
New model ([attributes])
When you create a model instance, you canAttributesPass the initial value. These values will be carried out on the model.SetIf your model definesInitializeMethod, which is called when an instance is created.
NewBook ({
Title: "One Thousand and One Night ",
Author: "Scheherazade"
});
Get
Model. Get (attribute)
Obtains the current value of the specified attribute of the model, as shown in figureNote. Get ('title ')
Set
Model. Set (attributes, [Options])
Set one or more attributes for the model. If the value of attribute changes the status of the model,ChangeThe event will be triggered unless you passOptionsThe parameter is set{Silent: Tru}. The change event of a specific attribute is also triggered, So if you only care about the changes to a specific attribute, you can only subscribe to specific events, suchChagne: TitleOrChange: Content
Note. Set ({Title: "October 12", content: "lorem ipsum dolor sit Amet ..."});
If the model definesValidateMethod. This method is called when set is called. If verification fails, the attributes of the model will not change.SetMethod returns false. You can use options to pass an error callback to capture this situation. You can also subscribe toErrorEvent.
Escapte
Model. Escape (attribute)
If it is easy to useGet, Returns the original attribute. If you want to insert the retrieved value into HTML, you can useEscape
VaRHacker =NewBackbone. Model ({
Name: "<SCRIPT> alert ('xsss') </SCRIPT>"
});
Alert (hacker. Escape ('name '));
Has
Model. Has (attribute)
Returns true if the specified attribute is not null or undefined.
If(Note. Has ("title ")){
...
}
Unset
Model. unset (attribute, [Options])
Delete the specified attribute in the attributes key-value pair in the model, and the change event is triggered unless the silent is set through the options parameter.
Clear
Model. Clear ([Options])
Remove all attributes in the model and trigger the change event, unless the silent is set through options.
ID
Model. ID
A special attribute of the model. It can be any string (integer or GUID). If you set the ID attribute for the model, it will become a direct attribute of the model: get is not required ). You canCollectionsAnd use it to generate the default URL of the model ).
CID
Model. CID
A special attribute of the model. It is a unique identifier automatically assigned when the model is created for the first time. When the model has not been saved to the server, the model has no ID attribute. In this case, it needs to be displayed on the UI. Therefore, a client ID is required, which is similarC1, C2, C3...
Attributes
Model. Attributes
AttributesAttribute is used to save the internal status of the model. Please useSetInstead of modifying it directly. If you want to obtain it, useTojsonMethod.
Ults
Model. defaults or model. defaults ()
UltsYou can specify the default attributes for the model by using a hash (or method. When a model instance is created, the default value is used for attributes that are not set.
VaRMeal = backbone. model. Extend ({
Defaults :{
"Appetizer": "Caesar salad ",
"Entree": "ravioli ",
"Dessert": "Cheesecake"
}
});
Alert ("dessert will be" + (NewMeal). Get ('dessert '));
Remember that in Javascript, objects are passed through references, so the default values contained in objects are shared by all instances.
Tojson
Model. tojson ()
Returns a copy of The JSON object of Model. attributes. It can be used for persistence, serialization, or when the view processes model data. This name is not very good, because it does not return a JSON string, but you can use JSON. stringify_method) to obtain the JSON string
VaRArtist =NewBackbone. Model ({
Firstname: "Wassily ",
Lastname: "kandinsky"
});
Artist. Set ({birthday: "December 16,186 6 "});
Alert (JSON. stringify (artist ));
Fetch
Model. Fetch ([Options])
Reset the model status through the server. It is often used when there is no data in the model, or the data in the model must always be the latest version of the server. If the data pulled from the server is different from the current data of the model, a change event is triggered. It can be used in the options parameter.SuccessAndErrorThe callback function is used to handle fetch success and failure. The model and Response parameters are passed in when these two Callbacks are executed.
//Poll every 10 seconds to keep the channel model up-to-date.
Setinterval (Function(){
Channel. Fetch ();
},10000 );
Save
Mode. Save ([attributes], [Options])
PassBackbone. syncSave the model to the database (or another persistent layer ).AttributesParameter, only the attribute mentioned here is saved, and the attribute not mentioned will not be updated. If the model containsValidateMethod, and the verification fails, the model will not be saved successfully. If Model.IsnewIf this parameter is set to trueCreate(Http post). If the model already exists on the serverUpdate(Http put)
The following example demonstratesBackbone. syncWhen the model is saved for the first timeCreateMethod, and the second saveUpdateMethod.
Backbone. Sync =Function(Method, model ){
Alert (method + ":" + JSON. stringify (model ));
Model. ID = 1;
};
VaRBook =NewBackbone. Model ({
Title: "The Rough Riders ",
Author: "Theodore Roosevelt"
});
Book. Save ();
Book. Save ({Author: "Teddy "});
SaveCan be set in the second options parameterSuccessAndErrorCallback is used to process the success and failure of SAVE. The two callback parameters pass in the mode and Response parameters. If the model containsValidateIf verification fails, the server returns a non-200 response, or an incorrect text or JSON response (for example, the response returned by the server cannot be in JSON format ).
Book. Save ({Author: "F. D. R."}, {error:Function(){...}});
Destroy
Model. Destroy ([Options])PassBackbone. syncDestroy model on the server,OptionsSuccess and error Callbacks are acceptable in the parameters. The destroy method triggersDestroyEvent, and the event bubbles up toCollections
Book. Destroy ({success:Function(Model, response ){
...
}});
Validate
Model. Validate (attributes)
This method is not defined by default. We encourage you to define it to implement your custom verification logic. This method will be calledSetAndSaveAnd pass the attributes to be saved or set. If these attributes are verified, the method returns nothing. If the verification fails, a string or object can be returned ). If a verification error occurs, set and save will not be executed and will triggerErrorEvent.
VaRChapter = backbone. model. Extend ({
Validate:Function(Attrs ){
If(Attrs. End <attrs. Start ){
Return"Can't end before it starts ";
}
}
});
VaROne =NewChapter ({
Title: "Chapter one: the beginning"
});
One. BIND ("error ",Function(Model, error ){
Alert (model. Get ("title") + "" + error );
});
One. Set ({
Start: 15,
End: 10
});
ErrorEvents can be processed with coarse granularity, but if you want to save a model in another view to explicitly handle errors, you can directly specify error callback in the Save or set method to handle errors and block them.ErrorEvent trigger.
Account. Set ({access: "unlimited "},{
Error:Function(Model, error ){
Alert (error );
}
});
URL
Model. URL ()
Returns the relative URL of the resource of the model on the server. If your model does not use the URL automatically generated by backbone for synchronization, overwrite this method to implement your own logic. By default, if the model is in the collection, the generated URL is as follows:/[Collection. url]/[model. ID]If the model is not in collections, the generated URL is as follows:/[Urlroot]/model. ID
To generate a URL through collection. url, make sure you have defined it. Or defineUrlrootAll instances of the model share the property. If the model ID is 101Backbone. CollectionThe URL of is/Document/7/Notes, Will generate/Documents/7/Notes/101
Urlroot
Model. urlroot
If the model is not in the collection, specifyUrlrootTo make the defaultURLMethod can generate similar/[/Urlroot]/IDSuch a URL.
VaRBook = backbone. model. Extend ({urlroot: '/Book '});
VaRSolaris =NewBook ({ID: "1083-lem-solaris "});
Alert (Solaris. URL ());
Parse
Model. parse (response)
ParseInFetchAndSaveWhen the server returns data, this method is passed into the original response object. You need to return the attribute key-value pair to the Set Method of the model. By default, this method does not perform any operations, and simply returns a JSON response. If you already have an existing API that does not conform to the data format required by the Model, You can overwrite this method and use the custom logic to convert the returned data. If you want to use an existing API, you can even define the Sync method in the model to fully define the crud behavior of a specific model)
(Note: Some ror text is omitted here)
Clone
Model. Clone ()
Returns a model instance with the same attributes.
Isnew
Mode. isnew ()
Indicates whether the model is saved to the server. If the model has no ID attribute, it is considered not saved to the server.
Change
Model. Change ()
Manually triggeredChangeIf you set silent: True to prevent the change event from being triggered during the set operation, you can call the change method once after the set operation.
Haschanged
Model. haschanged ([attribute])
Whether the model has changed after the last change event is triggered. If attribute is specified, it indicates whether the attribute has changed.
Note that this method is generally used in the following situations, that is, to check whether the specified attribute has changed in the change callback.
Book. BIND ("change ",Function(){
If(Book. haschanged ("title ")){
...
}
});
Changeattributes
Model. changeattributes ([attributes])
If the attributes parameter is specified, the changed attributes are returned. In this way, you can obtain the attributes that will be modified to the server and selectively synchronize data to the server.
Previous
Model. Previous (attribute)
InChangeIn Event Callback, it can access the old value of the specified attribute.
VaRBill =NewBackbone. Model ({
Name: "Bill Smith"
});
Bill. BIND ("Change: Name ",Function(Model, name ){
Alert ("changed name from" + bill. Previous ("name") + "to" + name );
});
Bill. Set ({name: "Bill Jones "});
Previusattributes
Model. previusattributes ()
Returns the attributes copy before the model change. It is generally used to compare the differences between multiple versions of the model and roll back the attributes to the previous version when an error occurs.