EmberJS:如何更新模型属性

时间:2013-04-28 16:52:13

标签: ember.js

我有一个由Rails后端提供的消息列表。我需要的是当按下“toggle_visibility”动作按钮时,它将切换“public_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上,但我一直无法使它工作。

1 个答案:

答案 0 :(得分:2)

您可以使用ArrayController#itemController并为ModelArray中的单个记录定义控制器。然后,您必须在Array Controller中指定负责单个对象的Object Controller,您必须在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> 

(见fiddle

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