【问题标题】:Ember.js Controller Property IssueEmber.js 控制器属性问题
【发布时间】:2026-01-04 15:00:01
【问题描述】:

我正在 Ember.js 中构建应用程序,但在监控我向用户显示的属性时遇到问题。当用户登录时,我正在查询 API 以获取具有名为“isTrue”的字段的消息数量,并查看有多少值为“true”。

当用户登录系统时,我通过 init: function() 从应用程序控制器中的 cookie 中获取 ID

然后,此数据将显示在应用程序模板中。这是最好的方法吗?我遇到一个问题,当用户单击按钮以将记录从“isNew”==“true”更改为“isNew”==“false”时,属性未正确更新。这是做到这一点的最好方法,还是从 Ember 的角度来看,我做错了?

App.ApplicationController = Ember.Controller.extend({

    messageCount: null,

    init: function() {

        var test = 0;

        //get the cookie
        //query an API to retrieve a set of records to check if a specific field is marked as true
        //Compute the messageCount based on the number of records that are marked as true and set test equal to the message count. 

        this.set("messageCount", test);

    getMessages: function() {

        //repeat the code from the init function
    }

    actions: {

        markAsRead: function() {
            getMessages();
        }
    }

})

【问题讨论】:

  • “isNew”在哪里发挥作用?当您单击操作“markAsRead”时?属性(我猜是'messageCount')如何更新,仅在客户端或服务器上?我想我只是看不到您要更改记录的位置...
  • @Hana 'isNew' 存储在服务器上,并在每次用户登录时通过 API 进行查询,或者他们通过传播到 markAsRead 函数的操作将消息标记为已读。跨度>

标签: javascript ember.js


【解决方案1】:

在这个简单的To Do List example 中检查他们如何跟踪已完成任务的数量。

你应该像这样设置你的属性:

messageCount: function () {
    return this.filterProperty('isNew', true).get('length');
}.property('path.to.my.messages.array.@each.isNew'),

现在不用手动设置了,会自动更新的。

【讨论】:

  • 当属性值存储在服务器上时,您将如何合并它?每次用户单击 markAsRead 时,该记录的属性“isNew”通过 API 调用更改为 false,然后重新读取记录并相应更新属性 messageCount。