Ember multiple property changes but want to trigger single event

依然范特西╮ 提交于 2020-01-01 02:40:15

问题


I have a ArrayController for date picker with properties to and from. Now when user selects a new date range from the UI both to and from value changes.

So a function which observers on to and from is trigger twice for a single change in date range.

I want to trigger the function only one every date range change. Any suggestions how to do that with ember

    app = Ember.Application.create();

    app.Time = Ember.ArrayController.create({

        to: null,
        from: null,
        rootElement: "#time",

        debug1: function() {
            this.set('to', 1);
            this.set('from', 2);
        },

        debug2: function() {
            this.setProperties( {
                'to': 3,
                'from': 4
            });
        },

        debug3: function() {
            this.beginPropertyChanges();
            this.set('to', 5);
            this.set('from', 6);
            this.endPropertyChanges();
        },

        search: function() {
            alert('called');
        }.observes('to', 'from')
    });

View in JS Fiddle


回答1:


Perhaps you can introduce a computed property on from and to, and then plug the observer on this property. As CPs are cached by default, I think the observer will be triggered only once.

date: function(){
 // return the computed date
}.property('from', 'to')

dateDidChange: function(){

}.observes('date')

EDIT Thanks to your fiddle, it seems to work using setProperties, or begin/end propertyChanges http://jsfiddle.net/Sly7/zf2q3/1/




回答2:


You can wrap observer in a Em.run.once

_dateDidChange: function(){
  Ember.run.once(this, 'dateDidChange');
}.observes('from', 'to'),

dateDidChange: function() {
  // should be called only once
}


来源:https://stackoverflow.com/questions/13316538/ember-multiple-property-changes-but-want-to-trigger-single-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!