ember.jsember.js-view

How to display post's delete button for only post's author in Ember.js


Hello I've been stuck for days how to display a post's delete button only for the post's author in Ember.js (I'm using ember-cli to build this). I don't know where to put the logic of "When hovering a post (list), if the post's author is equal to currently logged in user, then display the delete button" I am lost. Please help me.

in template app/templates/posts.hbs

{{#each}}
  <div class="eachPost">
    {{#view 'posts'}}
    <div class="postProfilePhoto">
      {{#link-to 'users' }}
      <img src="" alt="Profile Photo">
      {{/link-to}}
    </div>
    <div class="eachPostContent">
      <p class="postAuthor"><strong>{{user.id}}</strong></p>
      <p class="postContent">{{body}}</p>
      <span class="timePosted"><em>somtimes ago</em></span>
      {{#if view.entered}}{{#if isAuthor}}   
        <a class="deletePost" {{action "removePost" this}}>Delete</a>
      {{/if}}{{/if}}
    </div>
    {{/view}}
  </div>
{{/each}}

in views app/views/posts.js

var Posts = Ember.View.extend({
  classNames: ['eachPostContent'],
  mouseEnter: function(event){
    this.set('entered', true);
    this.get('controller').send('isAuthor', this.get('post').user);
  },
  mouseLeave: function(){
    this.set('entered', false);
  }
});

export default Posts;

in controller app/controllers/posts.js

var PostsController = Ember.ArrayController.extend({
    ...
    isAuthor: function(user){
      if(this.get('session').user !== null && user === this.get('session').user){
        return true;
      } else {
        return false;
        console.log('You are not author');
      }
    }
  }
});

export default PostsController;

SOLVED

in app/templates/posts.hbs

{{#each itemController="post"}}
  <div class="eachPost">

created app/controllers/post.js

var PostController = Ember.ObjectController.extend({
  isAuthor: function(){
    return this.get('user') === this.get('session').user;
  }.property('user')
});

export default PostController;

delete following code from app/views/posts.js this.get('controller').send('isAuthor', this.get('post').user);

and deleted isAuthor function from app/controllers/posts.js


Solution

  • As mentioned above, you'll want to use an itemController

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

    And then in the itemController you will create a computed property that checks the user id against the author id of the post

    var PostController = Ember.ObjectController.extend({
        isAuthor: function(){
          //assuming the user property exists on an individual post model
          return this.get('user') === this.get('session').user;
        }.property('user')
    })