Ember.js 选择集成 [英] Ember.js Chosen integration

查看:14
本文介绍了Ember.js 选择集成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经完成了一个示例 Ember.js 与 Chosen (https://github.com/harvesthq/chosen) 的集成

I've done a sample Ember.js integration with Chosen (https://github.com/harvesthq/chosen)

咖啡脚本:

App.ChosenSelectView = Em.Select.extend({
  didInsertElement: ->
    @_super()
    @$().chosen()
    # Assumes optionLabelPath is something like "content.name"
    @addObserver(@get("optionLabelPath").replace(/^content/, "content.@each"), ->  @contentDidChange())
  contentDidChange: ->
    # 2 ticks until DOM update
    Em.run.next(this, (-> Em.run.next(this, (-> @$().trigger("liszt:updated")))))
})

困扰我的事情是我不知道在触发 Chosen 小部件上的更新之前需要多长时间.从我的实验来看,2 个运行循环是可以的,但也许有更好的方法?

The thing that bothers me is I don't have a good idea about how much time do I need before triggering update on the Chosen widget. From my experiments 2 run loops is ok, but maybe there is a better way for the whole thing?

jsfiddle 的完整示例:http://jsfiddle.net/oruen/qfYPy/

Full example at jsfiddle: http://jsfiddle.net/oruen/qfYPy/

推荐答案

我认为问题在于您的观察者收到通知的时间有点过早,这意味着更改尚未写入 DOM.

I think the problem is that your observer is notified kind of too early, meaning that the changes have not yet been written to the DOM.

我稍微修改了一下,最后我想出了一个解决方案,它在 chosen 的事件之前调用 Ember.run.sync()插件被触发,见http://jsfiddle.net/pangratz666/dbHJb/

I've hacked a little around and in the end I came up with a solution, which calls Ember.run.sync() before the event for the chosen plugin is triggered, see http://jsfiddle.net/pangratz666/dbHJb/

把手:

<script type="text/x-handlebars" data-template-name="selectTmpl" >
    {{#each items tagName="select" }}
        <option {{bindAttr value="id"}} >{{name}}</option>    
    {{/each}}
</script>​

JavaScript:

App = Ember.Application.create({});

App.items = Ember.ArrayProxy.create({
    content: [Ember.Object.create({
        id: 1,
        name: 'First item'
    }), Ember.Object.create({
        id: 2,
        name: 'Second Item'
    })]
});

Ember.View.create({
    templateName: 'selectTmpl',
    itemsBinding: 'App.items',

    didInsertElement: function() {
        this.$('select').chosen();
    },

    itemsChanged: function() {
        // flush the RunLoop so changes are written to DOM?
        Ember.run.sync();
        // trigger the 'liszt:updated'
        Ember.run.next(this, function() {
            this.$('select').trigger('liszt:updated');
        });
    }.observes('items.@each.name')
}).append();

Ember.run.later(function() {
    // always use Ember.js methods to acces properties, so it should be 
    // `App.items.objectAt(0)` instead of `App.items.content[0]`
    App.items.objectAt(0).set('name', '1st Item');
}, 1000);​

这篇关于Ember.js 选择集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆