简体   繁体   中英

ember.js using itemController with each helper doesnt work as expected

How should i change the following code to work as expected, so doesnt change the completedness of other todos if i completed one?

itemController="todo" claimed to wrap each item in an own controllers but fails to do so.

index.html

    <script type="text/x-handlebars" id="todos">
    <ul>
        {{#each controller itemController="todo"}}
        <li>{{#link-to 'todo' this}}{{job}} -- {{#if isCompleted}}Completed{{else}}Incomplete{{/if}}{{/link-to}}</li>
        {{/each}}
    </ul>
    {{outlet}}
</script>
<script type="text/x-handlebars" id="todo">
    <p>Job: {{job}} -- {{#if isCompleted}}Completed{{else}}Incomplete{{/if}}</p>
    <button {{action 'complete' controller}}>Complete</button>
</script>

app.js

App = Ember.Application.create();

App.Router.map(function() {
  this.resource('todos', function() {
    this.resource('todo', { path: ':todo_id' })
  });
});

App.IndexRoute = Ember.Route.extend({
    redirect: function() { this.transitionTo('todos'); }
});

App.TodosRoute = Ember.Route.extend({
    model: function() {
        return todos;
    }
});

App.TodoRoute = Ember.Route.extend({
    model: function(params) {
        return todos.findBy('id', params.todos_id);
    }
});

App.TodosController = Ember.ArrayController.extend({
});

App.TodoController = Ember.ObjectController.extend({
    isCompleted: false,
    actions: {
        complete: function() {
            this.set('isCompleted',true);
        }
    }
});

var todos = [{id: '1', job: 'running'}, {id: '2', job: 'swimming'}, {id: '3', job: 'study'}];

I believe that you are mixing things

1 you have a list of todos each backed by ist own controller in the App.TodosRoute but in the App.TodoRoute you have another instance of the todoController, since the property is at the controller level, you are viewving the property setted for the 4th instance of the controller, the one reponsible for the todoRoute that is singleton.

You can move the property to the model and everything will goes well.

App.TodoController = Ember.ObjectController.extend({

    actions: {
        complete: function() {
            this.set('isCompleted',true);
        }
    }
});

var todos = [{id: '1', job: 'running',isCompleted: false}, {id: '2', job: 'swimming',isCompleted: false}, {id: '3', job: 'study',isCompleted: false}];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM