Search code examples
javascriptember.jsember-controllers

how to trigger Emberjs actions defined in itemController


Is there way a way to trigger an action defined in the itemController. When I trigger the action with <button {{action 'inItem' }}>, it throws Uncaught Error: Nothing handled the event 'inItem'.. If I set the target for the action with <button {{action 'inItem' target=item}}> , it throws the error, Uncaught TypeError: Cannot read property 'apply' of undefined.

How do I trigger the action defined in the itemController.

App = Ember.Application.create({
  LOG_TRANSITIONS: true
});

App.Router.map(function(){
   this.resource('posts');           
               
 });

App.PostsRoute = Ember.Route.extend({
  model: function(){
    return [
      {title: 'success'},
      {title: 'winning'},
      {title: 'breakthrough'}
    ];
  }
  
});

App.PostsController = Ember.Array.extend({
  itemController: 'post'
});
App.PostController = Ember.ObjectController.extend({
  isSelected: false,
  
  actions: {
    inItem: function(){
       this.set('isSelected', true);
      //alert('hi');
    }
  }
  
});
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.js"></script>
<script src="http://builds.emberjs.com.s3.amazonaws.com/tags/v1.0.0/ember.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <script type='text/x-handlebars' id='application'>
    {{#link-to 'posts'}} All posts {{/link-to}}
    {{outlet}}
   </script>
  
   <script type='text/x-handlebars' data-template-name='posts'>
   
     <br>
     {{#each item in controller }}
         
       {{#if item.isSelected}}
         {{item.title}}
       {{/if}}
       
       <br>
       
       <button {{action 'inItem' target=item}} {{bind-attr class="isSelected"}}> call itemcontroller action </button>


     {{/each}}
     
     
  </script>
    
</body>
</html>


Solution

  • Your controller should be extending ArrayController, not Array.

    App.PostsController = Ember.ArrayController.extend({
      itemController: 'post'
    });
    

    http://emberjs.jsbin.com/nabuwo/1/edit