问题
I have this posts.hbs:
{{#each model as |post|}}
<a href="#" {{action 'openWriteModal' post}}>
<h3>{{post.title}}</h3>
{{post.text}}
{{post.author.name}}
</a>
{{/each}}
Then I open my write-modal.hbs:
{{input value=model.title size="40" escape-press='close'}}
{{model.author.name}}
{{input value=model.text size="70" escape-press='close'}}
<button {{action 'close'}}>Close</button>
<button {{action 'save' model}}>Save</button>
Now, this is my components/write-modal.js:
export default Ember.Component.extend({
actions: {
close: function() {
return this.sendAction('close');
},
save(model) {
model.set("text", model.get("text"));
model.save().then(this.sendAction('close'));
}
}
});
here is the posts.js:
export default Ember.Route.extend({
model() {
return this.store.findAll('post');
},
actions: {
openWriteModal(post) {
return this.render('modal', {
outlet: 'modal',
into: 'application',
model: this.store.findRecord('post', post.id, { reload: true }),
controller: 'application'
});
},
closeWriteModal() {
return this.disconnectOutlet({
outlet: 'modal',
parentView: 'application'
});
},
saveWriteModal(model) {
model.save();
},
......
model(params) {
return this.store.query('post', params);
}
});
in my application.hbs:
{{outlet}}
{{outlet "modal"}}
and finally modal.hbs:
{{write-modal model=model close='closeWriteModal' save='saveWriteModal'}}
but I got this error: "Uncaught TypeError: Cannot read property 'save' of undefined"
How to fix this?
回答1:
You are sending "POST" record as an argument
{{#each model as |post|}}
<a href="#" {{action 'openWriteModal' "----post----"}}>
<h3>{{post.title}}</h3>
{{post.text}}
{{post.author.name}}
</a>
{{/each}}
This is an ember record. And then you're trying to find the exact same POST
Instead of using (u need to specify "directory/model_name" not DS record instance)
model: this.store.findRecord('post', post.id, { reload: true }),
Use
return this.render('modal', {
outlet: 'modal',
into: 'application',
model: post
controller: 'application'
});
Not sure if this helps your problem, let me know.
来源:https://stackoverflow.com/questions/32870407/ember-2-model-save-from-component-my-modal-hbs