Wednesday 15 August 2012

javascript - EmberJS set defaultValue from parent's model -



javascript - EmberJS set defaultValue from parent's model -

i need set defaultvalue of cost attribute cost of item. don't want utilize computedproperty because when item's cost change, transaction_detail's cost changed too, , scenario set price value on first time & shouldn't changed.

here transactiondetail.js.

var transactiondetail = ds.model.extend({ transaction: ds.belongsto('transaction'), item: ds.belongsto('item', { async: true }), borrowed_at: borrowedat, max_returned_at: maxreturnedat, returned_at: ds.attr('date'), price: ds.attr('number', { defaultvalue: function( detail) { homecoming detail.get('item.price'); // expect item's price, actual null } }), });

and below item.js

var item = ds.model.extend({ name: ds.attr('string'), is_available: ds.attr('boolean', { defaultvalue: true }), price: ds.attr('number', { defaultvalue: 0 }) });

update: after read this, add together file on initializers/reopen-store.js , edit content below:

import ds 'ember-data'; export function initialize(container, application) { var store = container.lookup('store:main'); store.reopen({ createrecord: function(type, properties) { if (type === 'transactiondetail') { if (typeof properties.price !== 'number') { properties.price = properties.item.get('price'); } } homecoming this._super.apply(this, arguments); }.on('createrecord') }); }; export default ds.store.extend({ name: 'reopen-store', initialize: initialize });

but when debugger; on model, this.get('item.price') still undefined. idea?

update 2:

thanks gjk response. reply still no luck me. here app/store.js:

import ds 'ember-data'; export default ds.store.extend({ init: function() { console.log('init called!'); homecoming this._super.apply(this, arguments); }, createrecord: function(type, properties) { console.log('prepare createrecord!'); debugger; if (type === 'transactiondetail') { if (typeof properties.price !== 'number') { properties.price = properties.item.get('price'); } } homecoming this._super.apply(this, arguments); } });

in console, output init called!. no 'prepare createrecord!' , debugger not triggered in chrome. idea?

in defaultvalue function, item.price coming null because item relationship hasn't been initialized yet. personally, take care of in store when create record, not in model.

app.store = ds.store.extend({ createrecord: function(type, properties) { if (type === 'transactiondetail') { if (typeof properties.price !== 'number') { properties.price = properties.item.get('price'); } } homecoming this._super.apply(this, arguments); } });

a bit more error checking required, idea. if cost isn't given @ time of creation, fill in , allow store handle rest.

javascript ember.js ember-data

No comments:

Post a Comment