Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a property which is observable but not run observable function for few cases in EmberJS

Tags:

ember.js

Is there anyway we can avoid running observable code in few cases?

How i tried? The only way i found to avoid is by adding new properties to the view as flags which will if checked before running the observable method code.

This is the basic jsfiddle link am providing with basic observer functionality HTML

<script type="text/x-handlebars" data-template-name="application">
  {{view MyApp.MyContainerView name="Santa Claus"}}
</script>
<script type="text/x-handlebars" data-template-name="foo">
  {{view.testProp}}
</script>

JS

MyApp = Ember.Application.create({
    autoinit: false
});

MyApp.router = Ember.Router.create({
    root: Ember.Route.extend({
        index: Ember.Route.extend({
            route: '/'
        })
    })
});

MyApp.ApplicationController = Ember.Controller.extend({});

MyApp.MyContainerView = Em.ContainerView.extend({
    childViews: ['foo'],

    foo: Em.View.extend({
       testProp: 100,
  testPropObservable: function(){
    console.log("Prop Observed");
  }.observes('testProp'),
        init: function() {
            this._super();
            this.set('testProp', 200);//i want to avoid obeserver here
        },
        templateName: 'foo'
    })
});

MyApp.initialize(MyApp.router);
like image 860
thecodejack Avatar asked Jan 09 '13 11:01

thecodejack


1 Answers

One alternative is to add/remove observers at runtime. Given the above example, you can prevent observer from being fired during init() by calling this.addObserver after the value has been initialized

    foo: Em.View.extend({
       testProp: 100,
       testPropDidChange: function(){
         console.log("Value changed to: ", this.get('testProp'));
       },
       init: function() {
         this._super();
         this.set('testProp', 200);//i want to avoid obeserver here
         this.addObserver('testProp', this.testPropDidChange)
        },
        templateName: 'foo'
    })

See this jsfiddle for a working example: http://jsfiddle.net/NSMj8/1/

There is a good overview of observers in the ember guides: http://emberjs.com/guides/object-model/observers/

More info on how to add/remove observers is available in the API docs for Ember.Observable: http://emberjs.com/api/classes/Ember.Observable.html

like image 181
Mike Grassotti Avatar answered Jan 03 '23 16:01

Mike Grassotti