1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- // 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();
- }
- }
- );
- /**
- * @see Model.url
- */
- $(function () {
- const onChange = (change, x) => {
- console.log('On change', change.changed);
- };
- // Create a model instance to load it by ID. Let it be global for console use.
- 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();
- });
|