Ember.js 使用自定义插件选择:如何绑定两者?
在我们的应用程序中,我们用jQuery插件替换了标准的select,以便能够在CSS中设置select的样式。我试图让它与灰烬,但我的解决方案是真的肮脏。有没有合适的方法 我认为关键问题是这种插件需要在页面中呈现HTML来更新自己。然而,Ember绑定在HTML实际呈现在页面中之前启动Ember.js 使用自定义插件选择:如何绑定两者?,ember.js,Ember.js,在我们的应用程序中,我们用jQuery插件替换了标准的select,以便能够在CSS中设置select的样式。我试图让它与灰烬,但我的解决方案是真的肮脏。有没有合适的方法 我认为关键问题是这种插件需要在页面中呈现HTML来更新自己。然而,Ember绑定在HTML实际呈现在页面中之前启动 Ember.Select.reopen({ didInsertElement: function(){ this.$().selectBox(); // Create the jQuery
Ember.Select.reopen({
didInsertElement: function(){
this.$().selectBox(); // Create the jQuery plugin
},
valueChanged: function(){
this.$().selectBox('value', this.get('value')); // Update the plugin value
}.observes('value'),
contentChanged: function(){
this.set('value', "-10"); // Fake value, just to force the cache. Othwerwise it won't refresh if the previous value was also "0".
this.set('value', "0"); // Default value for the new content.
// Option 1: manually "re-create" the plugin using 'content' - it fails with:
// Uncaught Error: Cannot perform operations on a Metamorph that is not in the DOM.
// And anyway it means 'content' needs to have a specific format which is not great.
var contentAsJson = {};
this.get('content').forEach(function(val){contentAsJson[val.get('id')] = val.get('displayName')});
this.$().selectBox('destroy');
this.$().selectBox();
this.$().selectBox('options', contentAsJson);
this.$().selectBox('value', this.get('value'));
// Options 2: wait for the actual HTML to be rendered with a timer. It "works" but it is terrible I guess
// to rely on a timer.
var self = this.$();
setTimeout(function(){self.selectBox('refresh')}, 100);
}.observes('content')
});
我意识到你不需要听值转换器,因为selectBox已经在积极地更新dom元素和插件本身。valueChanged observer中的一个简单跟踪可以告诉您很多事情 基于你的问题,我提出了这个小片段。事实上,我认为这实际上就像你原来的方法
我认为只设置超时是可以的,因为您需要等待内容首先呈现。刷新不要太重。非常感谢莱昂内尔的帮助!不幸的是,它并不完全有效,至少不完全有效。我的目标是拥有一个完整的绑定。我的意思是,如果您以编程方式更改select本身,它也应该更改selectBox。这就是为什么——我认为——你确实需要观察“价值”。我分叉了您的JSFIDLE,请参见此处:。错误链接,抱歉:继续如果您更改select控件本身而不是selectBox,您将看到更改未应用于selectBox。此外,更改“选择”的内容时,“选定”字段不会更新。
Ember.Select.reopen({
didInsertElement: function(){
this.set('value', null);
this.$().selectBox(); // Create the jQuery plugin
},
contentChanged: function() {
//Ember.run.next is equivalent to setTimeout(fn,1);
//We want to wait for contentChanged first to finish
//then rerender selectBox.
//To get the structure of key-value is too tedious so
//just rerender it instead.
Ember.run.next(this, function() {
this.$().selectBox('refresh');
});
//Reset the selection value if you insist
//this.set('value', null);
}.observes('content')
});