我采用了一个简单的Ember应用程序。目前,我在路线上通过模型方法加载一组位置,如下所示:
Hex.LocationsbysectionsRoute = Ember.Route.extend({
model: function(params) {
return $.getJSON("/arc/v1/api/all-locations").then( function(response){
return response.map(function (child) {
return Hex.Location.create(child);
});
});
}
});
我想在底部添加一个搜索按钮,以便为特定部分添加位置。我知道我可以使用transitionTo,但我真的只是想把它放到DOM中 - 这看起来非常简单,但很难在网上找到一个有效的例子。
类似的东西:
<script type="text/x-handlebars" id="locationsbysections">
<input id='hex-ember-location-val' /><button {{action 'searchForLocations'}}>search</button>
</script>
但我不确定如何处理searchForLocations
操作并将结果导入UI。我会在路线上使用该模型吗?我在思考这个问题但是我如何将Promise传递给模板呢?
Hex.LocationsbysectionsController = Ember.ArrayController.extend({
actions: {
searchForLocations: function() {
var query=$('#hex-ember-location-val').val();
$.getJSON("/arc/v1/api/locations/query_by_sections/" + query).then( function(response){
var items=[];
$.each(response, function(idx, val){
var location=Hex.Location.create(val);
items.push(location);
console.log(location);
});
});
}
}
});
我能够将它放入items数组中,但是如何将其渲染到原始位置的分段模板中呢?看起来路由器的model
方法不是这样做的,但我怎么能让它工作呢?
我尝试过这样的事情:
{{#if hasSearchItems}}
<div>there are {{items.length}} search resutls!!!</div>
{{#each items}}
<div>{{name}} <button {{action "addToSection" this}}>add to section</button></div>
{{/each}}
{{else}}
<div>there are no search results</div>
{{/if}}
然后在Controller中管理hasSearchItems
变量,但没有骰子。
THX
答案 0 :(得分:1)
如果你不使用真正的余烬数据模型,你最终可以将模型留空并在setupController中设置你的属性:
Hex.LocationsbysectionsRoute = Ember.Route.extend({
model: function(params) {return null},
setupController: function(controller, model) {
$.getJSON("/arc/v1/api/all-locations").then(function(response) {
var locations = response.map(function (child) {
return Hex.Location.create(child);
});
controller.set("locations", locations)
});
}
}
<script type="text/x-handlebars" id="locationsbysections">
{{#each location in locations}}
<div>{{location.name}}</div>
etc...
{{/each}}
</script>
通过这种方式,您可以毫无问题地覆盖locations
属性。
<script type="text/x-handlebars" id="locationsbysections">
...
{{input type='text' value=searchInput}}
<button {{action 'searchForLocations'}}>search</button>
</script>
Hex.LocationsbysectionsController = Ember.ArrayController.extend({
searchInput: "",
actions: {
searchForLocations: function() {
var that = this;
$.getJSON("/arc/v1/api/locations/query_by_sections/" + that.get("searchInput")).then(function(response) {
var locations = response.map(function (child) {
return Hex.Location.create(child);
});
that.set("locations", locations)
});
});
}
});