1

我有一个 Rails 后端提供的消息列表。我需要的是当按下“toggle_visibility”操作按钮时,它会切换“publicly_viewable”属性。这意味着,进行相应的 REST 调用(以影响数据库)并更改相应缓存消息的状态。这是我到目前为止的位置。

这是我到目前为止所得到的,最终在调试控制台上结束:

# app.js
App.Store = DS.Store.extend({
  revision: 12,
  adapter: DS.RESTAdapter.extend({
    url: 'http://localhost:3000'
  })
});

App.Message = DS.Model.extend({
  body: DS.attr('string'),
  mobile_number: DS.attr('string'),
  publicly_viewable: DS.attr('boolean'),
  created_at: DS.attr('date')
});

App.Router.map(function() {
  this.resource('messages');
});

App.MessagesRoute = Ember.Route.extend({
  model: function() { return App.Message.find() }
});

App.MessagesController = Ember.ArrayController.extend({
  toggle_visibility: function(){
    debugger;
  }
});

# index.html
{{#each model}}
<button class="close" {{action toggle_visibility this}}><i class="icon-eye-close"></i></button>
<p class="message_body lead">{{body}}</p>
<small class="source_number">from {{mobile_number}}, received {{date created_at}}</small>
{{/each}}

在过去的几个小时里,我一直在阅读 Ember 指南,虽然我对有哪些不同的课程有所了解,但我仍然无法清楚地想象如何去做。特别是,我不确定这应该是路由问题还是控制器,而且我知道如果它是控制器责任,我知道它应该在 ObjectController 上,但我一直无法让它工作。

4

1 回答 1

2

您可以ArrayController#itemControllerModelArray. 然后您必须在数组控制器中指定负责单个对象的对象控制器,您也必须在 Handlebars 中引用该对象控制器。你可以这样做:

JS:

App.MessageController = Ember.ObjectController.extend({
    visibilityClass: function() {
        var visibility = this.get('model.publiclyViewable');
        return 'toggle-visibility mdi-action-visibility%@'.fmt(
            visibility ? '':'-off'
        );
    }.property('model.publiclyViewable'),
    actions: {
        toggleVisibility: function() { 
            var model = this.get('model');
            model.toggleProperty('publiclyViewable');
            model.save();
        }
    }
});

车把:

<script type="text/x-handlebars" data-template-name="messages">
    <!-- 
    At this point the {{each}} helper will know how to lookup for
    the controller simply by it's name
    -->
    {{#each model itemController="message"}}
    <div class="panel panel-primary">
        <div class="panel-heading">
            <div class="pull-left">
                <h3 class="panel-title">{{title}}</h3>
            </div>
            <div class="pull-right">
                <a {{action 'toggleVisibility'}}>
                    <i class={{visibilityClass}} style="color: #FFF"></i>
                </a>
            </div>
        </div>
        <div class="panel-body">
          {{body}}
        </div>
        <div class="panel-footer">
          <i class="mdi-communication-quick-contacts-dialer"></i> {{mobileNumber}}
          <i class="mdi-notification-event-note"></i> {{createdAt}} 
        </div>
    </div>

    {{/each}}
</script> 

(见小提琴

注意:更新到 Ember 1.11.x-beta 并稍微更改了代码

于 2013-04-28T17:28:12.940 回答