12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- // Create a model class.
- const TodoItem = Backbone.Model.extend({
- defaults: {
- description: "Empty todo",
- status: "incomplete",
- },
- // RESTful web service, RoR flavor.
- urlRoot: '/server/todos',
- toggleStatus(view) {
- this.set('status', (this.get('status') === 'incomplete')
- ? 'complete'
- : 'incomplete');
- this.save();
- }
- }
- );
- function todoModelSingleExample() {
- const onChange = (change, x) => {
- console.log('On change', change.changed);
- };
- // Create a model instance to load it by ID.
- const todoItem = new TodoItem({ id: 1 });
- // Listeners
- todoItem.on('change', onChange);
- // Skip listener during a change. Notice the value format.
- todoItem.set({ 'description': 'some other description' }, {silent: true});
- // Remove listener.
- //todoItem.off('change', onChange);
- /* Built-in events
- change - when any attribute is modified
- change:<attr> - when <attr> is modified
- destroy - when the model is destroyed
- sync - when the model successfully synced with the server
- error - when model save or validation fails
- all - on any event
- */
- // Check default attribute pre-fetch.
- const defaultDescription = todoItem.get('description');
- // Access the server at /server/todos/1 (urlRoot + '/' + item.id).
- const x = todoItem.fetch({ async: false });
- // Manipulate attributes.
- const description = todoItem.get('description');
- todoItem.set('status', 'complete');
- // Save on server.
- todoItem.save();
- // Destroy on server.
- // todoItem.destroy();
- return todoItem;
- }
- /**
- * @see Model.url
- */
- $(function () {
- // Let it be global for console use.
- globalTodoItem = todoModelSingleExample();
- });
|