KO 初心者: 次の検索結果モジュールの実装では、マッピング プラグインを使用して searchData JSON 配列をビュー モデルにマッピングします。また、いくつかのデータの操作されたバージョンを表示するために、2 つの追加のプロパティを作成しました。
define('searchresults', ['ko', 'lodash', 'datacontext', 'moment'], function (ko, _, datacontext, moment) {
var get = function (term) {
amplify.request("appsearch", { 'searchterm': term }, function (searchData) {
var viewModel = {};
var mapping = {
'untilNow' : {
create: function (options) {
var innerModel = ko.mapping.fromJS(options.data);
innerModel.untilNow = moment(innerModel.lastSentDate()).fromNow();
return innerModel;
}
},
'iconClass': {
create: function (options) {
var innerModel = ko.mapping.fromJS(options.data);
innerModel.iconClass = "icon-" + innerModel.type();
return innerModel;
}
}
};
viewModel.searchResults = ko.mapping.fromJS(searchData, mapping.untilNow);
ko.applyBindings(viewModel);
});
};
return {
get: get
};
});
これは、次のテンプレートに入力するために呼び出されます。
<div id="contacts" class="view animated fadeInLeft">
<h3>Search results for {{#routeData}}{{term}}{{/routeData}}</h3>
<ul data-bind="template: { name: 'searchresults-template', foreach: searchResults }"></ul>
</div>
<script type="text/html" id="searchresults-template">
<!--<li data-bind="attr: {'class': iconClass}">-->
<li>
<h4><span data-bind="text: type"></span></h4>
<p><b>When created:</b> <span data-bind="text: untilNow"></span></p>
<p><b>By:</b> <span data-bind="text: createdBy"></span></p>
<p><b>Company:</b> <span data-bind="text: company"></span></p>
<hr/>
</li>
</script>
<script>
require(['searchresults'], function (searchresults) {
var searchTerm = "{{#routeData}}{{term}}{{/routeData}}";
searchresults.get(searchTerm);
});
</script>
私が理解できないのは:
- どうやら
mapping.untilNow
KO は {} しか期待していないように見えるので、マッピングだけを使用することはできません。その結果、未定義になるため、iconClass を使用できません。 - innerModel の実装を繰り返さなければならないというのは、何が間違っているのでしょうか。プロパティ KO スタイルからそれをどのように抽象化できますか!
- また、ko.mapping を viewModel.searchResults だけでなく、viewModel だけでなく、mt テンプレートを反復処理する唯一の方法に割り当てる必要があるのは少し危険です。
KO の基本的な側面を理解していないのでしょうか? これは、データを取得してテンプレートに適用し、その一部を操作するメソッドを追加する正しい方法ですか?
本当にありがとう
searchData のサンプル ストリーム:
[
{
"type": "Campaign",
"lastSentDate": "/Date(634873003155215782)/",
"createdBy": "Stephen Parker",
"company": "Virgin Media"
},
{
"type": "Person",
"lastSentDate": "/Date(1198908717056-0700)/",
"createdBy": "John Smith",
"company": "Concep LTD"
},
{
"type": "Campaign",
"lastSentDate": "\/Date(1239018869048)\/",
"createdBy": "Stephen Parker",
"company": "Virgin Media"
},
{
"type": "Company",
"lastSentDate": "/Date(1198908717056-0700)/",
"createdBy": "Stephen Parker",
"company": "Virgin Media"
}
]