我有4個帖子。每個人都有一個標題和一個作者。現在,它按作者排序。我想點擊一個按鈕(比如按標題排序),並按照標題而不是作者對信息進行排序。
到目前爲止,我知道我正在整理作者和標題,並且模型正在更新。問題是在視圖中顯示更新的信息。出於某種原因,我認爲如果我只是做了this.set('model', newModel)
這個新信息會自動顯示。事實並非如此。
這是我的代碼。
practice.hbs
{{outlet}}
<button {{action "sortTitles"}}>Sort by Title</button>
<button {{action "sortAuthors"}}>Sort by Author</button>
{{#each model as |post|}}
<h2>Title: {{post.title}}</h2>
<h3>Author: {{post.author}}</h3>
{{/each}}
路由/ practice.js
import Ember from 'ember';
export default Ember.Route.extend({
model() {
var myArray = [{
title: "Learning EmberJS",
author: "Erik Hatchett"
},{
title: "Controllers are Dead",
author: "Frank Treacy"
},{
title: "Diddly Doo",
author: "No I'm Adrian"
},{
title: "Yisss",
author: "Dank Sir"
}];
myArray.sort(function(a,b) {
if (a.author > b.author) {
console.log(a + " is greater than " + b);
return 1;
}
else {
console.log(b + " is greater than " + a);
return -1;
}
});
if ("dat" < "cat") {
console.log("ayy");
}
console.log(myArray[2]);
return myArray;
}
});
控制器/ practice.js
import Ember from 'ember';
var sortByAuthor = function(a,b) {
if (a.author > b.author) {
console.log(a + " is greater than " + b);
return 1;
}
else {
console.log(b + " is greater than " + a);
return -1;
}
};
var sortByTitle = function(a,b) {
if (a.title > b.title) {
console.log(a + " is greater than " + b);
return 1;
}
else {
console.log(b + " is greater than " + a);
return -1;
}
};
export default Ember.Controller.extend({
actions: {
sortAuthors() {
var myModel = this.get('model');
console.log(myModel[0].author);
myModel.sort(sortByAuthor);
console.log(myModel[0].author);
this.set('model', myModel);
},
sortTitles() {
var myModel = this.get('model');
myModel.sort(sortByTitle);
console.log(myModel[0].title);
this.set('model', myModel);
}
}
});
這些信息絕對正在排序,模型肯定正在更新。它似乎不顯示排序的信息。
請看我更新的答案,它現在包含一個代碼示例 –