所以我尝试使用ajax向我的服务器发送自定义操作,并在回调中更新emberJS模型。我的控制器代码如下所示:
PlatformUI.CampaignItemController = Ember.ObjectController.extend({
actions: {
deleteCampaign: function(){
var campaign = this.get('model');
campaign.deleteRecord();
campaign.save();
},
startCampaign: function(){
var campaign = this.get('model');
$.ajax({
url: '/campaigns/' + campaign.get('id') + '/campaign_start.json',
type: 'GET',
success: function(data, textStatus, xhr) {
campaign.set('status', data.started);
//campaign.save();
},
error: function(xhr, textStatus, errorThrown) {
console.log(xhr);
alert('start campaign failed');
}
});
}
}
});
我的模型看起来像这样:
PlatformUI.Campaign = DS.Model.extend({
name: DS.attr('string'),
status: DS.attr('string'),
updated_at: DS.attr('date'),
user_id: DS.attr('number'),
created_at: DS.attr('date'),
started: function(){
return this.get('status') == 'true';
}.property()
});
编辑:添加模板:
<div class="page-header">
<h1> Campaigns
List
<a role="button" class="btn btn-primary" href="/campaigns/new">Create New</a>
</h1>
</div>
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Status</th>
<th>Last updated</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{{#each campaign in model itemController="CampaignItem"}}
<tr>
<td>{{campaign.id}}</td>
<td>{{campaign.name}}</td>
<td>{{ternary campaign.status "Started" "Stopped"}}</td>
<td>{{campaign.updated_at}}</td>
<td>
<a class="btn btn-primary" {{bind-attr href=campaign.edit_url}}>Edit</a>
<a class="btn btn-danger" {{action "deleteCampaign"}}>Delete</a>
{{#if campaign.started}}
<a class="btn btn-primary" {{bind-attr href=campaign.stop_url}}>Stop</a>
{{else}}
<a class="btn btn-primary" {{action "startCampaign"}}>Start</a>
{{/if}}
</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
问题是我执行该操作时没有刷新视图。我是emberJS的新手,所以我不知道模型是否真的更新过。
答案 0 :(得分:2)
您需要让started
知道它是由status
计算出来的,因此它知道在status
发生更改时会重新计算。
您可以通过在依赖项列表中包含status
来完成此操作。
started: function(){
return this.get('status') == 'true';
}.property('status')