我有一个简单的ember.js文本字段,我正在尝试添加自动对焦
{{view PersonApp.SearchField placeholder="search..." valueBinding="searchText"}}
PersonApp.SearchField = Ember.TextField.extend({
});
我可以在javascript中添加它,还是像模板本身中的属性一样简单?
答案 0 :(得分:29)
<强>更新强>
现在更多最新版本的Ember支持这种内置功能,因此您不再需要重新打开TextField来添加attributeBinding。自2014年1月起(提交fdfe8495),您只需在模板中使用HTML5自动对焦属性:
{{input value=search type="text" placeholder="Search" autofocus="autofocus"}}
这是simple jsfiddle demonstration。
以前的解决方案:
您还可以重新打开TextField以允许绑定自动聚焦属性:
Ember.TextField.reopen({
attributeBindings: ['autofocus']
});
然后在你的模板中:
{{input value=search type="text" placeholder="Search" autofocus="autofocus"}}
答案 1 :(得分:10)
还可以选择在TextField上使用HTML5自动聚焦属性。
PersonApp.SearchField = Ember.TextField.extend({
attributeBindings: ['autofocus'],
autofocus: 'autofocus'
});
有关自动对焦字段的详情,请参阅documentation on Mozilla Developer Network:
答案 2 :(得分:8)
自动对焦意味着我们立即开始关注文本框?你想要didInsertElement
。
didInsertElement: function() {
this.$().focus();
}
答案 3 :(得分:2)
我将这个方法包装在一个小的1kb包中,直接在模板中更优雅地解决这个问题,无需进一步编码:
<body>
<!-- all the libraries -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/ember.js/1.2.0/ember.min.js"></script>
<script src="http://rawgithub.com/AndreasPizsa/ember-autofocus/master/dist/ember-autofocus.min.js"></script>
<!-- your template -->
<script type="text/x-handlebars">
Hello, world! {{ input }}
:
: more elements here
:
{{ autofocus }}
</script>
<!-- your app -->
<script>
Ember.Application.create();
</script>
</body>
套餐位于https://github.com/AndreasPizsa/ember-autofocus
(或bower install ember-autofocus
)。享受!