问题
I have a template which is backed by a model. It is a tree list view which has the first level folders.
I have an action handler which is used to update the sub-child any of the first level folder. From the action I need to update the model so that the sub-child is updated in the template.
I can add another first level folder by directly updating the model using pushObject.
How can I add/update the sub-child nodes of any parent level folders.
In template:
<script type="text/x-handlebars">
<h2> Welcome to Ember.js</h2>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
<ul>
{{#each item in model}}
<li>{{item.foldername}}</li>
{{/each}}
</ul>
<button {{action 'createFolder'}}>Add First Level Folder</button>
<button {{action 'createSubFolder'}}>Add Sub Folder</button>
</script>
In my app.js:
App = Ember.Application.create();
App.Router.map(function() {
// put your routes here ;
});
App.folder = Ember.Object.extend();
App.IndexRoute = Ember.Route.extend({
model: function() {
return [{'foldername': 'Folder 1'}, {'foldername': 'Folder 2'}, {'foldername': 'Folder 3'} ];
},
actions: {
createFolder: function () {
var obj = App.folder.create({'foldername': 'Folder 4'});
this.modelFor('index').pushObject(obj);
},
createSubFolder: function () {
var subObj = App.folder.create({'foldername': 'Sub Folder 1'});
//How to update this in the model below of any first level folder.
}
}
});
JSBIN Demo Link
回答1:
You need to render recursively using partials.
<script type="text/x-handlebars" data-template-name="index">
<ul>
{{#each model}}
{{partial "tree"}}
{{/each}}
</ul>
</script>
<script type="text/x-handlebars" data-template-name="_tree">
<li>{{foldername}}</li>
<ul>
{{#each children}}
{{partial "tree"}}
{{/each}}
</ul>
</script>
Here is a working demo.
来源:https://stackoverflow.com/questions/24385933/updating-ember-nested-model-and-template