Ember数据保存方法,创建与更新

时间:2014-10-08 13:38:17

标签: authentication ember.js ember-data

我无法弄清楚Ember如何确定它是否应该更新或创建记录。我会假设它基于ID或商店条目,但它似乎是别的东西。代码示例澄清:

// this returns the user without making an api call
currentUser.get('store').find('user_detail', '49')

// this returns 49
currentUser.get('id')

// this returns true
currentUser.get('store').hasRecordForId('user_detail', 49)

// this issues a create to api/userDetails instead
// of updating /api/userDetails/49
currentUser.save()

// maybe this is a lead, not the 48 at the end
currentUser.toString()
// <EmberApp.UserDetail:ember461:48>

// it looks as though currentState is involved here
// http://emberjs.com/api/data/classes/DS.RootState.html
currentUser.currentState

// returns root.loaded.created.uncommitted
currentUser.get('currentState.stateName');

// also isNew is wrong and returns true
currentUser.get('isNew');

让我解释为什么我有这个问题。我的应用有一个当前用户。如果您注销我更新当前用户。所以我设置了Ember.currentUser.setProperties(newUserData)。我更新了currentUser对象,以便ember自动触发整个应用程序的更新。如果我要替换currentUser Ember.currentUser = newUser;什么都不会更新。如果我无法解决上述问题,交换用户对象的替代解决方案也将起作用。

这就是我处理全局用户状态的方式

container.register('user:current', Ember.currentUser);
// and handle updates via Ember.currentUser.setProperties()
application.inject('controller', 'user', 'user:current');
application.inject('route', 'user', 'user:current');

正确的解决方案将取代Ember.currentUser,但这样做不会触发更新。

2 个答案:

答案 0 :(得分:2)

新模型将isNewisDirty属性设置为true,需要更新的现有记录只会将isDirty设置为true。

答案 1 :(得分:2)

我建议您将用户推得更深一层而不是将其存储在Ember名称空间中,这样您就可以从其他任何地方设置它,但仍然会在注入期间注入它

var users = Em.Object.create({
  current: currentUser
});

container.register('users:current', users, {instantiate: false});
// and handle updates via Ember.currentUser.setProperties()
application.inject('controller', 'users', 'users:current');
application.inject('route', 'users', 'users:current');

然后,您可以在任何控制器上users.current访问/观看它,但您也可以使用this.users.set('current', newUser)进行设置,这会影响在任何控制器或路线上观看该属性的任何人。

示例:http://emberjs.jsbin.com/OxIDiVU/1145/edit

此外,您正在做的很多事情都是异步调用,应该使用promise模式来查看属性等。

相关问题