gpt4 book ai didi

Ember .js |在一个组件操作上通知其他组件

转载 作者:行者123 更新时间:2023-12-04 23:55:00 25 4
gpt4 key购买 nike

components section at Ember's guides有一个帖子摘要组件的演示,
单击一个 Post Summery 标题会打开其下方的内容。

我想添加功能以同时关闭任何其他打开的帖子摘要。

我的问题的目的是了解 ember 如何在不牺牲隔离的情况下在组件之间说话。

我想到的解决方案是:

  • 有一些包装组件以某种方式处理它
  • 触发一个像“post-summery:open”这样的事件并使其他组件在其上关闭(但随后它可以使用相同的组件与应用程序上的其他地方发生碰撞以用于不同用途)

  • 这是文档中的原始演示:
    http://jsbin.com/uyibis/1/edit

    这就是我使用 jQuery 实现行为的方式:
    http://jsbin.com/eremon/2/edit

    var $contents = $('.content').hide();

    $(document).on('click', '.title', function () {

    $contents.hide();
    $(this).next('.content').show();

    });



    enter image description here

    最佳答案

    这个问题在 Ember 中一直出现。我解决它的方法是跟踪 Controller 上哪个帖子是“打开的”,然后让每个项目的 View 根据该数据负责自己的状态。这样您就不必在每次切换帖子时手动重置每个帖子的状态。

    事实的规范来源是 Controller 。

    App.IndexController = Ember.ArrayController.extend({
    content: null,
    selectedPost: null // null means no post selected
    });

    我们通过模板将此信息连接到组件。
    <script type="text/x-handlebars" data-template-name="index">
    {{#each post in controller}}
    {{post-summary post=post selectedPost=selectedPost}}
    {{/each}}
    </script>

    <script type="text/x-handlebars" id="components/post-summary">
    <h3 {{action "toggleBody"}}>{{post.title}}</h3>
    {{#if isShowingBody}}
    <p>{{{post.body}}}</p>
    {{/if}}
    </script>

    现在可以通过属性计算给定帖子的正文可见性。
    App.PostSummaryComponent = Ember.Component.extend({
    post: null,
    selectedPost: null,

    isShowingBody: function() {
    return this.get('selectedPost') === this.get('post');
    }.property('selectedPost', 'post'),

    toggleBody: function() {
    this.set('selectedPost',
    this.get('isShowingBody') ? null : this.get('post'));
    }
    });

    Here's the jsfiddle .

    有人可能会争辩说,这不是一个理想的面向对象解决方案,但它极大地改善了我的 Ember 应用程序的结构和可维护性。通过让每个元素根据共同的事实来源负责自己的状态,您可以实现各种复杂的列表行为。

    关于 Ember .js |在一个组件操作上通知其他组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18035560/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com