我正在使用Ember製作玩具庫跟蹤應用程序。我正在重構一些代碼,並且這個sendAction出現了。 sendAction的高級用途是什麼?它是否導致更乾淨的代碼?我已經閱讀this。Ember.js。 sendAction的目的是什麼?它是如何工作的?它只是導致更乾淨的代碼?
對不起,如果Ember的問題有很多必要的代碼來閱讀。我認爲這些是這裏的相關文件。
快速注意,我有一個libraries.new路線,它加載了具有renderTemplate方法的路徑/庫/ new.js文件,該方法呈現一個表單模板(這個表單模板用於幾個不同的區域,所以這個DRYs up我的代碼)。由於我的路由處理有呈現庫/形式的renderTemplate功能,這是我的圖書館/表單模板:
<h2>{{title}}</h2>
<div class="row">
<div class="col-md-6">
{{library-item-form item=model buttonLabel=buttonLabel action='saveLibrary'}}
</div>
<div class="col-md-4">
{{#library-item item=model}}
<br/>
{{/library-item}}
</div>
</div>
問題:
- 庫項目形成分線有動作(這是什麼叫做?它是一個屬性?)屬性從它的上下文(庫/新的路由處理程序?)中通過'saveLibrary'操作
- 因爲這是組件的傳入操作,那就是當buttonClicked方法得到時被調用的動作由於buttonClicked方法調用sendAction,所以在庫項目表單組件中調用?
這是我的圖書館項目形成分js文件:
import Ember from 'ember';
export default Ember.Component.extend({
buttonLabel: 'Save',
actions: {
buttonClicked(param) {
this.sendAction('action', param);
}
}
});
這裏是我的圖書館項目,form.hbs組件模板。這是一個帶有提交按鈕的3輸入字段。提交按鈕有一個名爲buttonClicked:動作
<div class="form-horizontal">
<div class="form-group has-feedback {{if item.isValid 'has-success'}}">
<label class="col-sm-2 control-label">Name*</label>
<div class="col-sm-10">
{{input type="text" value=item.name class="form-control" placeholder="The name of the Library"}}
{{#if item.isValid}}<span class="glyphicon glyphicon-ok form-control-feedback"></span>{{/if}}
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Address</label>
<div class="col-sm-10">
{{input type="text" value=item.address class="form-control" placeholder="The address of the Library"}}
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Phone</label>
<div class="col-sm-10">
{{input type="text" value=item.phone class="form-control" placeholder="The phone number of the Library"}}
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" {{action 'buttonClicked' item}} disabled="{{unless item.isValid 'disabled'}}">{{buttonLabel}}</button>
</div>
</div>
</div>
哦最後,這是庫/新路由處理與saveLibrary行動:
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.createRecord('library');
},
setupController: function (controller, model) {
this._super(controller, model);
controller.set('title', 'Create a new library');
controller.set('buttonLabel', 'Create');
},
renderTemplate() {
this.render('libraries/form');
},
actions: {
saveLibrary(newLibrary) {
newLibrary.save().then(() => this.transitionTo('libraries'));
},
willTransition() {
let model = this.controller.get('model');
if (model.get('isNew')) {
model.destroyRecord();
}
}
}
});
最後問題
因此,正確地說,無論在動作屬性(saveLibrary)中傳遞到組件中的動作是當組件js文件(components/library-item-form.js)調用一個調用sendAction函數的動作(buttonClicked)?
sendAction的第一個參數是否被稱爲'action'?調用組件的行中的屬性是否必須被稱爲「操作」?
澄清總是有幫助 – Jwan622