您可以创建一个SearchModel
. SearchModel
会有一个方法,比如:“performSearch(string)”,它会触发你的 ajax 调用。当调用返回时,模型可以执行以下操作:
this.set("searchResults", ajaxResult)
并且您的视图可以绑定到模型的该属性:
// SearchResultsView
Backbone.View.extend({
initialize: function() {
this.model.on("change:searchResults", this.displayResults, this);
},
displayResults: function(model, results) {
// do whatever...
}
});
示例搜索表单视图以供参考:
Backbone.View.extend({
events: {
"submit": "formSubmitted"
},
formSubmitted: function(e) {
this.model.performSearch(e.target.value);
}
});
SearchModel
供参考的例子:
Backbone.Model.extend({
performSearch: function(string) {
// fire your ajax request. provide a bound
// _searchComplete as the callback
},
_searchComplete: function(results) {
this.set("searchResults", results);
}
});