我有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);
}
}
});
这些信息绝对正在排序,模型肯定正在更新。它似乎不显示排序的信息。
请看我更新的答案,它现在包含一个代码示例 –