如何在Ember.js中仅为帖子的作者显示帖子的删除按钮

时间:2014-05-26 10:05:46

标签: ember.js ember.js-view

您好我已经被困了几天如何仅为帖子的作者在Ember.js中显示帖子的删除按钮(我使用ember-cli来构建这个)。我不知道在哪里放置&#34; 的逻辑当悬停帖子(列表)时,如果帖子的作者等于当前登录的用户,则显示删除按钮< /强>&#34;我搞不清楚了。请帮帮我。

模板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}}

在观看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;

在控制器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;

解决

app/templates/posts.hbs

中的

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

创建app/controllers/post.js

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

export default PostController;

app/views/posts.js删除以下代码 this.get('controller').send('isAuthor', this.get('post').user);

并从isAuthor

删除了app/controllers/posts.js个功能

1 个答案:

答案 0 :(得分:2)

如上所述,您需要使用itemController

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

然后在itemController中,您将创建一个计算属性,根据帖子的作者ID检查用户ID

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')
})