1 <!DOCTYPE html><html><head><title>Sencha Documentation Project</title><link rel="stylesheet" href="../reset.css" type="text/css"><link rel="stylesheet" href="../prettify.css" type="text/css"><link rel="stylesheet" href="../prettify_sa.css" type="text/css"><script type="text/javascript" src="../prettify.js"></script></head><body onload="prettyPrint()"><pre class="prettyprint"><pre><span id='Ext-data.Model-method-constructor'><span id='Ext-data.Model'>/**
2 </span></span> * @author Ed Spencer
3 * @class Ext.data.Model
5 * <p>A Model represents some object that your application manages. For example, one might define a Model for Users, Products,
6 * Cars, or any other real-world object that we want to model in the system. Models are registered via the {@link Ext.ModelManager model manager},
7 * and are used by {@link Ext.data.Store stores}, which are in turn used by many of the data-bound components in Ext.</p>
9 * <p>Models are defined as a set of fields and any arbitrary methods and properties relevant to the model. For example:</p>
11 <pre><code>
13 extend: 'Ext.data.Model',
15 {name: 'name', type: 'string'},
16 {name: 'age', type: 'int'},
17 {name: 'phone', type: 'string'},
18 {name: 'alive', type: 'boolean', defaultValue: true}
21 changeName: function() {
22 var oldName = this.get('name'),
23 newName = oldName + " The Barbarian";
25 this.set('name', newName);
28 </code></pre>
30 * <p>The fields array is turned into a {@link Ext.util.MixedCollection MixedCollection} automatically by the {@link Ext.ModelManager ModelManager}, and all
31 * other functions and properties are copied to the new Model's prototype.</p>
33 * <p>Now we can create instances of our User model and call any model logic we defined:</p>
35 <pre><code>
36 var user = Ext.ModelManager.create({
43 user.get('name'); //returns "Conan The Barbarian"
44 </code></pre>
46 * <p><u>Validations</u></p>
48 * <p>Models have built-in support for validations, which are executed against the validator functions in
49 * {@link Ext.data.validations} ({@link Ext.data.validations see all validation functions}). Validations are easy to add to models:</p>
51 <pre><code>
53 extend: 'Ext.data.Model',
55 {name: 'name', type: 'string'},
56 {name: 'age', type: 'int'},
57 {name: 'phone', type: 'string'},
58 {name: 'gender', type: 'string'},
59 {name: 'username', type: 'string'},
60 {name: 'alive', type: 'boolean', defaultValue: true}
64 {type: 'presence', field: 'age'},
65 {type: 'length', field: 'name', min: 2},
66 {type: 'inclusion', field: 'gender', list: ['Male', 'Female']},
67 {type: 'exclusion', field: 'username', list: ['Admin', 'Operator']},
68 {type: 'format', field: 'username', matcher: /([a-z]+)[0-9]{2,3}/}
71 </code></pre>
73 * <p>The validations can be run by simply calling the {@link #validate} function, which returns a {@link Ext.data.Errors}
76 <pre><code>
77 var instance = Ext.ModelManager.create({
83 var errors = instance.validate();
84 </code></pre>
86 * <p><u>Associations</u></p>
88 * <p>Models can have associations with other Models via {@link Ext.data.BelongsToAssociation belongsTo} and
89 * {@link Ext.data.HasManyAssociation hasMany} associations. For example, let's say we're writing a blog administration
90 * application which deals with Users, Posts and Comments. We can express the relationships between these models like this:</p>
92 <pre><code>
94 extend: 'Ext.data.Model',
95 fields: ['id', 'user_id'],
98 hasMany : {model: 'Comment', name: 'comments'}
101 Ext.define('Comment', {
102 extend: 'Ext.data.Model',
103 fields: ['id', 'user_id', 'post_id'],
109 extend: 'Ext.data.Model',
114 {model: 'Comment', name: 'comments'}
117 </code></pre>
119 * <p>See the docs for {@link Ext.data.BelongsToAssociation} and {@link Ext.data.HasManyAssociation} for details on the usage
120 * and configuration of associations. Note that associations can also be specified like this:</p>
122 <pre><code>
124 extend: 'Ext.data.Model',
128 {type: 'hasMany', model: 'Post', name: 'posts'},
129 {type: 'hasMany', model: 'Comment', name: 'comments'}
132 </code></pre>
134 * <p><u>Using a Proxy</u></p>
136 * <p>Models are great for representing types of data and relationships, but sooner or later we're going to want to
137 * load or save that data somewhere. All loading and saving of data is handled via a {@link Ext.data.proxy.Proxy Proxy},
138 * which can be set directly on the Model:</p>
140 <pre><code>
142 extend: 'Ext.data.Model',
143 fields: ['id', 'name', 'email'],
150 </code></pre>
152 * <p>Here we've set up a {@link Ext.data.proxy.Rest Rest Proxy}, which knows how to load and save data to and from a
153 * RESTful backend. Let's see how this works:</p>
155 <pre><code>
156 var user = Ext.ModelManager.create({name: 'Ed Spencer', email: 'ed@sencha.com'}, 'User');
158 user.save(); //POST /users
159 </code></pre>
161 * <p>Calling {@link #save} on the new Model instance tells the configured RestProxy that we wish to persist this
162 * Model's data onto our server. RestProxy figures out that this Model hasn't been saved before because it doesn't
163 * have an id, and performs the appropriate action - in this case issuing a POST request to the url we configured
164 * (/users). We configure any Proxy on any Model and always follow this API - see {@link Ext.data.proxy.Proxy} for a full
167 * <p>Loading data via the Proxy is equally easy:</p>
169 <pre><code>
170 //get a reference to the User model class
171 var User = Ext.ModelManager.getModel('User');
173 //Uses the configured RestProxy to make a GET request to /users/123
175 success: function(user) {
176 console.log(user.getId()); //logs 123
179 </code></pre>
181 * <p>Models can also be updated and destroyed easily:</p>
183 <pre><code>
184 //the user Model we loaded in the last snippet:
185 user.set('name', 'Edward Spencer');
187 //tells the Proxy to save the Model. In this case it will perform a PUT request to /users/123 as this Model already has an id
189 success: function() {
190 console.log('The User was updated');
194 //tells the Proxy to destroy the Model. Performs a DELETE request to /users/123
196 success: function() {
197 console.log('The User was destroyed!');
200 </code></pre>
202 * <p><u>Usage in Stores</u></p>
204 * <p>It is very common to want to load a set of Model instances to be displayed and manipulated in the UI. We do this
205 * by creating a {@link Ext.data.Store Store}:</p>
207 <pre><code>
208 var store = new Ext.data.Store({
212 //uses the Proxy we set up on Model to load the Store data
214 </code></pre>
216 * <p>A Store is just a collection of Model instances - usually loaded from a server somewhere. Store can also maintain
217 * a set of added, updated and removed Model instances to be synchronized with the server via the Proxy. See the
218 * {@link Ext.data.Store Store docs} for more information on Stores.</p>
221 * @param {Object} data An object containing keys corresponding to this model's fields, and their associated values
222 * @param {Number} id Optional unique ID to assign to this model instance
224 Ext.define('Ext.data.Model', {
225 alternateClassName: 'Ext.data.Record',
228 observable: 'Ext.util.Observable'
235 'Ext.data.Operation',
236 'Ext.data.validations',
237 'Ext.data.proxy.Ajax',
238 'Ext.util.MixedCollection'
241 onClassExtended: function(cls, data) {
242 var onBeforeClassCreated = data.onBeforeClassCreated;
244 data.onBeforeClassCreated = function(cls, data) {
246 name = Ext.getClassName(cls),
247 prototype = cls.prototype,
248 superCls = cls.prototype.superclass,
250 validations = data.validations || [],
251 fields = data.fields || [],
252 associations = data.associations || [],
253 belongsTo = data.belongsTo,
254 hasMany = data.hasMany,
256 fieldsMixedCollection = new Ext.util.MixedCollection(false, function(field) {
260 associationsMixedCollection = new Ext.util.MixedCollection(false, function(association) {
261 return association.name;
264 superValidations = superCls.validations,
265 superFields = superCls.fields,
266 superAssociations = superCls.associations,
271 // Save modelName on class and its prototype
272 cls.modelName = name;
273 prototype.modelName = name;
275 // Merge the validations of the superclass and the new subclass
276 if (superValidations) {
277 validations = superValidations.concat(validations);
280 data.validations = validations;
282 // Merge the fields of the superclass and the new subclass
284 fields = superFields.items.concat(fields);
287 for (i = 0, ln = fields.length; i < ln; ++i) {
288 fieldsMixedCollection.add(new Ext.data.Field(fields[i]));
291 data.fields = fieldsMixedCollection;
293 //associations can be specified in the more convenient format (e.g. not inside an 'associations' array).
294 //we support that here
296 belongsTo = Ext.Array.from(belongsTo);
298 for (i = 0, ln = belongsTo.length; i < ln; ++i) {
299 association = belongsTo[i];
301 if (!Ext.isObject(association)) {
302 association = {model: association};
305 association.type = 'belongsTo';
306 associations.push(association);
309 delete data.belongsTo;
313 hasMany = Ext.Array.from(hasMany);
314 for (i = 0, ln = hasMany.length; i < ln; ++i) {
315 association = hasMany[i];
317 if (!Ext.isObject(association)) {
318 association = {model: association};
321 association.type = 'hasMany';
322 associations.push(association);
328 if (superAssociations) {
329 associations = superAssociations.items.concat(associations);
332 for (i = 0, ln = associations.length; i < ln; ++i) {
333 dependencies.push('association.' + associations[i].type.toLowerCase());
337 if (typeof data.proxy === 'string') {
338 dependencies.push('proxy.' + data.proxy);
340 else if (typeof data.proxy.type === 'string') {
341 dependencies.push('proxy.' + data.proxy.type);
345 Ext.require(dependencies, function() {
346 Ext.ModelManager.registerType(name, cls);
348 for (i = 0, ln = associations.length; i < ln; ++i) {
349 association = associations[i];
351 Ext.apply(association, {
353 associatedModel: association.model
356 if (Ext.ModelManager.getModel(association.model) === undefined) {
357 Ext.ModelManager.registerDeferredAssociation(association);
359 associationsMixedCollection.add(Ext.data.Association.create(association));
363 data.associations = associationsMixedCollection;
365 onBeforeClassCreated.call(me, cls, data);
367 cls.setProxy(cls.prototype.proxy || cls.prototype.defaultProxyType);
369 // Fire the onModelDefined template method on ModelManager
370 Ext.ModelManager.onModelDefined(cls);
375 inheritableStatics: {
376 <span id='Ext-data.Model-method-setProxy'> /**
377 </span> * Sets the Proxy to use for this model. Accepts any options that can be accepted by {@link Ext#createByAlias Ext.createByAlias}
378 * @param {String/Object/Ext.data.proxy.Proxy} proxy The proxy
381 setProxy: function(proxy) {
382 //make sure we have an Ext.data.proxy.Proxy object
383 if (!proxy.isProxy) {
384 if (typeof proxy == "string") {
389 proxy = Ext.createByAlias("proxy." + proxy.type, proxy);
391 proxy.setModel(this);
392 this.proxy = this.prototype.proxy = proxy;
397 <span id='Ext-data.Model-method-getProxy'> /**
398 </span> * Returns the configured Proxy for this Model
399 * @return {Ext.data.proxy.Proxy} The proxy
401 getProxy: function() {
405 <span id='Ext-data.Model-method-load'> /**
406 </span> * <b>Static</b>. Asynchronously loads a model instance by id. Sample usage:
407 <pre><code>
408 MyApp.User = Ext.define('User', {
409 extend: 'Ext.data.Model',
411 {name: 'id', type: 'int'},
412 {name: 'name', type: 'string'}
416 MyApp.User.load(10, {
418 failure: function(record, operation) {
419 //do something if the load failed
421 success: function(record, operation) {
422 //do something if the load succeeded
424 callback: function(record, operation) {
425 //do something whether the load succeeded or failed
428 </code></pre>
429 * @param {Number} id The id of the model to load
430 * @param {Object} config Optional config object containing success, failure and callback functions, plus optional scope
431 * @member Ext.data.Model
435 load: function(id, config) {
436 config = Ext.apply({}, config);
437 config = Ext.applyIf(config, {
442 var operation = Ext.create('Ext.data.Operation', config),
443 scope = config.scope || this,
447 callback = function(operation) {
448 if (operation.wasSuccessful()) {
449 record = operation.getRecords()[0];
450 Ext.callback(config.success, scope, [record, operation]);
452 Ext.callback(config.failure, scope, [record, operation]);
454 Ext.callback(config.callback, scope, [record, operation]);
457 this.proxy.read(operation, callback, this);
462 PREFIX : 'ext-record',
468 <span id='Ext-data.Model-method-id'> /**
469 </span> * Generates a sequential id. This method is typically called when a record is {@link #create}d
470 * and {@link #Record no id has been specified}. The id will automatically be assigned
471 * to the record. The returned id takes the form:
472 * <tt>&#123;PREFIX}-&#123;AUTO_ID}</tt>.<div class="mdetail-params"><ul>
473 * <li><b><tt>PREFIX</tt></b> : String<p class="sub-desc"><tt>Ext.data.Model.PREFIX</tt>
474 * (defaults to <tt>'ext-record'</tt>)</p></li>
475 * <li><b><tt>AUTO_ID</tt></b> : String<p class="sub-desc"><tt>Ext.data.Model.AUTO_ID</tt>
476 * (defaults to <tt>1</tt> initially)</p></li>
477 * </ul></div>
478 * @param {Ext.data.Model} rec The record being created. The record does not exist, it's a {@link #phantom}.
479 * @return {String} auto-generated string id, <tt>"ext-record-i++'</tt>;
483 var id = [this.PREFIX, '-', this.AUTO_ID++].join('');
490 <span id='Ext-data.Model-property-editing'> /**
491 </span> * Internal flag used to track whether or not the model instance is currently being edited. Read-only
497 <span id='Ext-data.Model-property-dirty'> /**
498 </span> * Readonly flag - true if this Record has been modified.
503 <span id='Ext-data.Model-cfg-persistanceProperty'> /**
504 </span> * @cfg {String} persistanceProperty The property on this Persistable object that its data is saved to.
505 * Defaults to 'data' (e.g. all persistable data resides in this.data.)
507 persistanceProperty: 'data',
512 <span id='Ext-data.Model-property-phantom'> /**
513 </span> * <tt>true</tt> when the record does not yet exist in a server-side database (see
514 * {@link #setDirty}). Any record which has a real database pk set as its id property
515 * is NOT a phantom -- it's real.
521 <span id='Ext-data.Model-cfg-idProperty'> /**
522 </span> * @cfg {String} idProperty The name of the field treated as this Model's unique id (defaults to 'id').
526 <span id='Ext-data.Model-property-defaultProxyType'> /**
527 </span> * The string type of the default Model Proxy. Defaults to 'ajax'
528 * @property defaultProxyType
531 defaultProxyType: 'ajax',
533 <span id='Ext-data.Model-property-fields'> /**
534 </span> * An array of the fields defined on this model
539 constructor: function(data, id) {
548 isArray = Ext.isArray(data),
549 newData = isArray ? {} : null; // to hold mapped array data if needed
551 <span id='Ext-data.Model-property-internalId'> /**
552 </span> * An internal unique ID for each Model instance, used to identify Models that don't have an ID yet
553 * @property internalId
557 me.internalId = (id || id === 0) ? id : Ext.data.Model.id(me);
563 <span id='Ext-data.Model-property-modified'> /**
564 </span> * Key: value pairs of all fields whose values have changed
570 me[me.persistanceProperty] = {};
572 me.mixins.observable.constructor.call(me);
574 //add default field values if present
575 fields = me.fields.items;
576 length = fields.length;
578 for (i = 0; i < length; i++) {
583 // Have to map array data so the values get assigned to the named fields
584 // rather than getting set as the field names with undefined values.
585 newData[name] = data[i];
587 else if (data[name] === undefined) {
588 data[name] = field.defaultValue;
592 me.set(newData || data);
593 // clear any dirty/modified since we're initializing
601 if (typeof me.init == 'function') {
605 me.id = me.modelName + '-' + me.internalId;
607 Ext.ModelManager.register(me);
610 <span id='Ext-data.Model-method-get'> /**
611 </span> * Returns the value of the given field
612 * @param {String} fieldName The field to fetch the value for
613 * @return {Mixed} The value
615 get: function(field) {
616 return this[this.persistanceProperty][field];
619 <span id='Ext-data.Model-method-set'> /**
620 </span> * Sets the given field to the given value, marks the instance as dirty
621 * @param {String|Object} fieldName The field to set, or an object containing key/value pairs
622 * @param {Mixed} value The value to set
624 set: function(fieldName, value) {
627 modified = me.modified,
629 field, key, i, currentValue;
632 * If we're passed an object, iterate over that object. NOTE: we pull out fields with a convert function and
633 * set those last so that all other possible data is set before the convert function is called
635 if (arguments.length == 1 && Ext.isObject(fieldName)) {
636 for (key in fieldName) {
637 if (fieldName.hasOwnProperty(key)) {
639 //here we check for the custom convert function. Note that if a field doesn't have a convert function,
640 //we default it to its type's convert function, so we have to check that here. This feels rather dirty.
641 field = fields.get(key);
642 if (field && field.convert !== field.type.convert) {
643 convertFields.push(key);
647 me.set(key, fieldName[key]);
651 for (i = 0; i < convertFields.length; i++) {
652 field = convertFields[i];
653 me.set(field, fieldName[field]);
658 field = fields.get(fieldName);
660 if (field && field.convert) {
661 value = field.convert(value, me);
664 currentValue = me.get(fieldName);
665 me[me.persistanceProperty][fieldName] = value;
667 if (field && field.persist && !me.isEqual(currentValue, value)) {
669 me.modified[fieldName] = currentValue;
678 <span id='Ext-data.Model-method-isEqual'> /**
679 </span> * Checks if two values are equal, taking into account certain
680 * special factors, for example dates.
682 * @param {Object} a The first value
683 * @param {Object} b The second value
684 * @return {Boolean} True if the values are equal
686 isEqual: function(a, b){
687 if (Ext.isDate(a) && Ext.isDate(b)) {
688 return a.getTime() === b.getTime();
693 <span id='Ext-data.Model-method-beginEdit'> /**
694 </span> * Begin an edit. While in edit mode, no events (e.g.. the <code>update</code> event)
695 * are relayed to the containing store. When an edit has begun, it must be followed
696 * by either {@link #endEdit} or {@link #cancelEdit}.
698 beginEdit : function(){
702 me.dirtySave = me.dirty;
703 me.dataSave = Ext.apply({}, me[me.persistanceProperty]);
704 me.modifiedSave = Ext.apply({}, me.modified);
708 <span id='Ext-data.Model-method-cancelEdit'> /**
709 </span> * Cancels all changes made in the current edit operation.
711 cancelEdit : function(){
715 // reset the modified state, nothing changed since the edit began
716 me.modified = me.modifiedSave;
717 me[me.persistanceProperty] = me.dataSave;
718 me.dirty = me.dirtySave;
719 delete me.modifiedSave;
725 <span id='Ext-data.Model-method-endEdit'> /**
726 </span> * End an edit. If any data was modified, the containing store is notified
727 * (ie, the store's <code>update</code> event will fire).
728 * @param {Boolean} silent True to not notify the store of the change
730 endEdit : function(silent){
734 delete me.modifiedSave;
737 if (silent !== true && me.dirty) {
743 <span id='Ext-data.Model-method-getChanges'> /**
744 </span> * Gets a hash of only the fields that have been modified since this Model was created or commited.
747 getChanges : function(){
748 var modified = this.modified,
752 for (field in modified) {
753 if (modified.hasOwnProperty(field)){
754 changes[field] = this.get(field);
761 <span id='Ext-data.Model-method-isModified'> /**
762 </span> * Returns <tt>true</tt> if the passed field name has been <code>{@link #modified}</code>
763 * since the load or last commit.
764 * @param {String} fieldName {@link Ext.data.Field#name}
767 isModified : function(fieldName) {
768 return this.modified.hasOwnProperty(fieldName);
771 <span id='Ext-data.Model-method-setDirty'> /**
772 </span> * <p>Marks this <b>Record</b> as <code>{@link #dirty}</code>. This method
773 * is used interally when adding <code>{@link #phantom}</code> records to a
774 * {@link Ext.data.Store#writer writer enabled store}.</p>
775 * <br><p>Marking a record <code>{@link #dirty}</code> causes the phantom to
776 * be returned by {@link Ext.data.Store#getModifiedRecords} where it will
777 * have a create action composed for it during {@link Ext.data.Store#save store save}
778 * operations.</p>
780 setDirty : function() {
786 me.fields.each(function(field) {
789 me.modified[name] = me.get(name);
795 markDirty : function() {
796 if (Ext.isDefined(Ext.global.console)) {
797 Ext.global.console.warn('Ext.data.Model: markDirty has been deprecated. Use setDirty instead.');
799 return this.setDirty.apply(this, arguments);
803 <span id='Ext-data.Model-method-reject'> /**
804 </span> * Usually called by the {@link Ext.data.Store} to which this model instance has been {@link #join joined}.
805 * Rejects all changes made to the model instance since either creation, or the last commit operation.
806 * Modified fields are reverted to their original values.
807 * <p>Developers should subscribe to the {@link Ext.data.Store#update} event
808 * to have their code notified of reject operations.</p>
809 * @param {Boolean} silent (optional) True to skip notification of the owning
810 * store of the change (defaults to false)
812 reject : function(silent) {
814 modified = me.modified,
817 for (field in modified) {
818 if (modified.hasOwnProperty(field)) {
819 if (typeof modified[field] != "function") {
820 me[me.persistanceProperty][field] = modified[field];
829 if (silent !== true) {
834 <span id='Ext-data.Model-method-commit'> /**
835 </span> * Usually called by the {@link Ext.data.Store} which owns the model instance.
836 * Commits all changes made to the instance since either creation or the last commit operation.
837 * <p>Developers should subscribe to the {@link Ext.data.Store#update} event
838 * to have their code notified of commit operations.</p>
839 * @param {Boolean} silent (optional) True to skip notification of the owning
840 * store of the change (defaults to false)
842 commit : function(silent) {
850 if (silent !== true) {
855 <span id='Ext-data.Model-method-copy'> /**
856 </span> * Creates a copy (clone) of this Model instance.
857 * @param {String} id (optional) A new id, defaults to the id
858 * of the instance being copied. See <code>{@link #id}</code>.
859 * To generate a phantom instance with a new id use:<pre><code>
860 var rec = record.copy(); // clone the record
861 Ext.data.Model.id(rec); // automatically generate a unique sequential id
862 * </code></pre>
865 copy : function(newId) {
868 return new me.self(Ext.apply({}, me[me.persistanceProperty]), newId || me.internalId);
871 <span id='Ext-data.Model-method-setProxy'> /**
872 </span> * Sets the Proxy to use for this model. Accepts any options that can be accepted by {@link Ext#createByAlias Ext.createByAlias}
873 * @param {String/Object/Ext.data.proxy.Proxy} proxy The proxy
876 setProxy: function(proxy) {
877 //make sure we have an Ext.data.proxy.Proxy object
878 if (!proxy.isProxy) {
879 if (typeof proxy === "string") {
884 proxy = Ext.createByAlias("proxy." + proxy.type, proxy);
886 proxy.setModel(this.self);
892 <span id='Ext-data.Model-method-getProxy'> /**
893 </span> * Returns the configured Proxy for this Model
894 * @return {Ext.data.proxy.Proxy} The proxy
896 getProxy: function() {
900 <span id='Ext-data.Model-method-validate'> /**
901 </span> * Validates the current data against all of its configured {@link #validations} and returns an
902 * {@link Ext.data.Errors Errors} object
903 * @return {Ext.data.Errors} The errors object
905 validate: function() {
906 var errors = Ext.create('Ext.data.Errors'),
907 validations = this.validations,
908 validators = Ext.data.validations,
909 length, validation, field, valid, type, i;
912 length = validations.length;
914 for (i = 0; i < length; i++) {
915 validation = validations[i];
916 field = validation.field || validation.name;
917 type = validation.type;
918 valid = validators[type](validation, this.get(field));
923 message: validation.message || validators[type + 'Message']
932 <span id='Ext-data.Model-method-isValid'> /**
933 </span> * Checks if the model is valid. See {@link #validate}.
934 * @return {Boolean} True if the model is valid.
937 return this.validate().isValid();
940 <span id='Ext-data.Model-method-save'> /**
941 </span> * Saves the model instance using the configured proxy
942 * @param {Object} options Options to pass to the proxy
943 * @return {Ext.data.Model} The Model instance
945 save: function(options) {
946 options = Ext.apply({}, options);
949 action = me.phantom ? 'create' : 'update',
951 scope = options.scope || me,
960 operation = Ext.create('Ext.data.Operation', options);
962 callback = function(operation) {
963 if (operation.wasSuccessful()) {
964 record = operation.getRecords()[0];
965 //we need to make sure we've set the updated data here. Ideally this will be redundant once the
966 //ModelCache is in place
968 record.dirty = false;
970 Ext.callback(options.success, scope, [record, operation]);
972 Ext.callback(options.failure, scope, [record, operation]);
975 Ext.callback(options.callback, scope, [record, operation]);
978 me.getProxy()[action](operation, callback, me);
983 <span id='Ext-data.Model-method-destroy'> /**
984 </span> * Destroys the model using the configured proxy
985 * @param {Object} options Options to pass to the proxy
986 * @return {Ext.data.Model} The Model instance
988 destroy: function(options){
989 options = Ext.apply({}, options);
993 scope = options.scope || me,
1002 operation = Ext.create('Ext.data.Operation', options);
1003 callback = function(operation) {
1004 if (operation.wasSuccessful()) {
1005 Ext.callback(options.success, scope, [record, operation]);
1007 Ext.callback(options.failure, scope, [record, operation]);
1009 Ext.callback(options.callback, scope, [record, operation]);
1012 me.getProxy().destroy(operation, callback, me);
1016 <span id='Ext-data.Model-method-getId'> /**
1017 </span> * Returns the unique ID allocated to this model instance as defined by {@link #idProperty}
1018 * @return {Number} The id
1021 return this.get(this.idProperty);
1024 <span id='Ext-data.Model-method-setId'> /**
1025 </span> * Sets the model instance's id field to the given id
1026 * @param {Number} id The new id
1028 setId: function(id) {
1029 this.set(this.idProperty, id);
1032 <span id='Ext-data.Model-method-join'> /**
1033 </span> * Tells this model instance that it has been added to a store
1034 * @param {Ext.data.Store} store The store that the model has been added to
1036 join : function(store) {
1037 <span id='Ext-data.Model-property-store'> /**
1038 </span> * The {@link Ext.data.Store} to which this Record belongs.
1040 * @type {Ext.data.Store}
1045 <span id='Ext-data.Model-method-unjoin'> /**
1046 </span> * Tells this model instance that it has been removed from the store
1048 unjoin: function() {
1052 <span id='Ext-data.Model-method-afterEdit'> /**
1054 * If this Model instance has been {@link #join joined} to a {@link Ext.data.Store store}, the store's
1055 * afterEdit method is called
1057 afterEdit : function() {
1058 this.callStore('afterEdit');
1061 <span id='Ext-data.Model-method-afterReject'> /**
1063 * If this Model instance has been {@link #join joined} to a {@link Ext.data.Store store}, the store's
1064 * afterReject method is called
1066 afterReject : function() {
1067 this.callStore("afterReject");
1070 <span id='Ext-data.Model-method-afterCommit'> /**
1072 * If this Model instance has been {@link #join joined} to a {@link Ext.data.Store store}, the store's
1073 * afterCommit method is called
1075 afterCommit: function() {
1076 this.callStore('afterCommit');
1079 <span id='Ext-data.Model-method-callStore'> /**
1081 * Helper function used by afterEdit, afterReject and afterCommit. Calls the given method on the
1082 * {@link Ext.data.Store store} that this instance has {@link #join joined}, if any. The store function
1083 * will always be called with the model instance as its single argument.
1084 * @param {String} fn The function to call on the store
1086 callStore: function(fn) {
1087 var store = this.store;
1089 if (store !== undefined && typeof store[fn] == "function") {
1094 <span id='Ext-data.Model-method-getAssociatedData'> /**
1095 </span> * Gets all of the data from this Models *loaded* associations.
1096 * It does this recursively - for example if we have a User which
1097 * hasMany Orders, and each Order hasMany OrderItems, it will return an object like this:
1102 * status: 'shipped',
1109 * @return {Object} The nested data set for the Model's loaded associations
1111 getAssociatedData: function(){
1112 return this.prepareAssociatedData(this, [], null);
1115 <span id='Ext-data.Model-method-prepareAssociatedData'> /**
1117 * This complex-looking method takes a given Model instance and returns an object containing all data from
1118 * all of that Model's *loaded* associations. See (@link #getAssociatedData}
1119 * @param {Ext.data.Model} record The Model instance
1120 * @param {Array} ids PRIVATE. The set of Model instance internalIds that have already been loaded
1121 * @param {String} associationType (optional) The name of the type of association to limit to.
1122 * @return {Object} The nested data set for the Model's loaded associations
1124 prepareAssociatedData: function(record, ids, associationType) {
1125 //we keep track of all of the internalIds of the models that we have loaded so far in here
1126 var associations = record.associations.items,
1127 associationCount = associations.length,
1128 associationData = {},
1129 associatedStore, associatedName, associatedRecords, associatedRecord,
1130 associatedRecordCount, association, id, i, j, type, allow;
1132 for (i = 0; i < associationCount; i++) {
1133 association = associations[i];
1134 type = association.type;
1136 if (associationType) {
1137 allow = type == associationType;
1139 if (allow && type == 'hasMany') {
1141 //this is the hasMany store filled with the associated data
1142 associatedStore = record[association.storeName];
1144 //we will use this to contain each associated record's data
1145 associationData[association.name] = [];
1147 //if it's loaded, put it into the association data
1148 if (associatedStore && associatedStore.data.length > 0) {
1149 associatedRecords = associatedStore.data.items;
1150 associatedRecordCount = associatedRecords.length;
1152 //now we're finally iterating over the records in the association. We do this recursively
1153 for (j = 0; j < associatedRecordCount; j++) {
1154 associatedRecord = associatedRecords[j];
1155 // Use the id, since it is prefixed with the model name, guaranteed to be unique
1156 id = associatedRecord.id;
1158 //when we load the associations for a specific model instance we add it to the set of loaded ids so that
1159 //we don't load it twice. If we don't do this, we can fall into endless recursive loading failures.
1160 if (Ext.Array.indexOf(ids, id) == -1) {
1163 associationData[association.name][j] = associatedRecord.data;
1164 Ext.apply(associationData[association.name][j], this.prepareAssociatedData(associatedRecord, ids, type));
1168 } else if (allow && type == 'belongsTo') {
1169 associatedRecord = record[association.instanceName];
1170 if (associatedRecord !== undefined) {
1171 id = associatedRecord.id;
1172 if (Ext.Array.indexOf(ids, id) == -1) {
1174 associationData[association.name] = associatedRecord.data;
1175 Ext.apply(associationData[association.name], this.prepareAssociatedData(associatedRecord, ids, type));
1181 return associationData;
1184 </pre></pre></body></html>