12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- // Create a model class.
- const TodoItem = Backbone.Model.extend({
- defaults: {
- description: "Empty todo",
- status: "incomplete",
- },
- // RESTful web service, RoR flavor.
- urlRoot: '/server/todos',
- // Default parse() implementation, not needed with RoR style APIs
- // parse: response => response,
- // Long format for arrow function to allow breakpoint setting in Chrome.
- parse: (response) => {
- const todo = response.todo;
- todo.description = todo.desc;
- delete todo.desc;
- return todo;
- },
- toJSON: function () {
- // Default version
- // return _.clone(this.attributes);
- let attrs = _.clone(this.attributes);
- attrs.desc = attrs.description;
- attrs = _.pick(attrs, 'desc', 'id', 'status');
- return { todo: attrs };
- },
- 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({todo: { id: 1 }}, { parse: true });
- // 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();
- });
|