如何更新 Ember 中的元素

How to update an element in Ember

我有一个页面,其中的数据按行显示。每行都有一个元素:停止或播放。此元素由 handlebars 中的以下代码驱动:

{{#if isactive}}
  <a {{bindAttr href="toggle"}}><span class="glyphicon glyphicon-play" aria-hidden="true"></span></a>
{{else}}
  <a {{bindAttr href="toggle"}}><span class="glyphicon glyphicon-stop" aria-hidden="true"></span></a>
{{/if}}

当用户单击 "Stop" 或 "Play" 图标时,我希望调用后端服务器、更新数据库并将图标更改为停止或播放的逻辑。我不确定如何在 Ember 中执行此操作。目前,我的 toggle 方法是这样的:

App.TestController = Ember.ObjectController.extend({
    toggle: function () {
        return "/my/backendserver/"+this.get('id')+"/toggle";
    }.property()
});

这有效,但是,它会重新加载整页。

问题

如何修改 toggle 方法,使其仅调用服务器(提供 id 作为参数,并在不重新加载完整页面的情况下将停止图标切换为播放,反之亦然?)

您可以删除if语句并在class中使用if语句,如果active为true,则显示播放图标,如果为false,则停止,并且在 span:

中调用动作
<a><span class="glyphicon {{if active 'glyphicon-play' 'glyphicon-stop'}}" {{action "toggle"}} aria-hidden="true"></span></a> 

任何阅读本文的人请注意:此答案已写入 Ember 1.0.0rc6,不应用作编写现代 Ember.

的示例

所以你需要使用一个动作而不是改变锚点的 href 属性。

在您的模板中:

{{#if isactive}}
  <button {{action 'toggle'}}><span class="glyphicon glyphicon-play" aria-hidden="true"></span></button>
{{else}}
  <button {{action 'toggle'}}><span class="glyphicon glyphicon-stop" aria-hidden="true"></span></button>
{{/if}}

在你的控制器中:

App.TestController = Ember.ObjectController.extend({
  isactive: false,
  actions: {
    toggle() {
      var _this = this;
      fetch('/my/backendserver/'+this.get('id')+'/toggle').then(function() {
        _this.toggleProperty('isactive');
      });
    }
  }
});

顺便说一下,我可能有一些语法细节错误,那个版本已经超过 6 年了,它在 JavaScript 时间里永远存在。而且我没有测试这个。