使用来自不同模板的相同手柄动作助手 - 最佳做法是什么

时间:2012-08-13 14:08:25

标签: ember.js handlebars.js

我有一个ember.js应用程序。它使用 posts.handlebars 显示对象列表(让我们称之为 Post 对象)。每个列表项都包含一个链接,用于显示帖子 post.handlebars )的详细信息。 列表项和详细信息页都包含删除链接,该链接从帖子的集合中删除对象。由于除了显示链接的标签外,实现没有区别,因此将其保持干燥是有意义的。

当前代码正在运行:

# router
App.Router = Em.Router.extend({
  ...
  "delete": function(router, event) {
    var post = event.context;
    if (confirm("Are you sure you want to delete the post with title '" + (post.get('title')) + "'?")) {
      post.deleteRecord();
      post.store.commit();
      App.router.transitionTo('posts.index');
    }

  }
});

# posts.handlebars
<ul>
{{#each post in controller}}
  <li>
    {{post.title}}
    <a {{action delete post}}>x</a>
  </li>
{{/each}}
</ul>

# post.handlebars
<p>{{title}}</p>
<a {{action delete content}}>Destroy</a>

但我不想重复包含删除操作的代码。

我的下一个最佳猜测是定义一个视图并在两个模板中重复使用它。 但是,现在我无法将 Post 对象作为上下文传递给操作,方法是将其移动到视图中(我可能会做一些事情)。 通过将事件从路由器移动到视图我得到它的工作,但这感觉不对。

我目前的解决方案如下:

App.DeletePostView = Em.View.extend({
  mouseUp: function(event) {
    var id, post;
    id = this.get('content.id');
    post = App.Post.find(id);
    if (confirm("Are you sure you want to delete the post with title '" + (post.get('title')) + "'?")) {
      post.deleteRecord();
      post.store.commit();
      App.router.transitionTo('posts.index');
    }
  }
});


# posts.handlebars
<ul>
{{#each post in controller}}
  <li>
        {{post.title}}
        {{#view App.DeletePostView contentBinding="post"}}
            x
        {{/view}}
    </li>
{{/each}}
</ul>

# post.handlebars
<p>{{title}}</p>
<div>
    {{#view App.DeletePostView contentBinding="this"}}
        Destroy
    {{/view}}
</div>

如果我想重新使用车把动作助手,是否有人知道是否有更好的方法?

0 个答案:

没有答案