2013-01-09 26 views
11

有沒有辦法在少數情況下避免運行可觀察代碼?如何在EmberJS中設置一個可觀察但不能運行可觀測函數的屬性

我怎麼試過? 我發現要避免的唯一方法是通過向視圖添加新屬性作爲標誌,如果在運行可觀察方法代碼之前檢查它們將會檢查它們。

這是基本的jsfiddle鏈接我基本觀測功能提供 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); 

回答

11

一種替代方法是添加/在運行時刪除觀察員。 http://jsfiddle.net/NSMj8/1/

有一個很好的概述:鑑於上面的例子中,你可以通過調用this.addObserver價值已初始化後

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' 
    }) 

看到這個的jsfiddle的工作例如防止觀察者由init()期間被解僱在餘燼指南觀察員:http://emberjs.com/guides/object-model/observers/

如何添加/刪除觀察家

更多信息在Ember.Observable API文檔可用:http://emberjs.com/api/classes/Ember.Observable.html

+0

啊h,你只是更快:),+ 1順便說一句:) –

+0

該代碼只是一個例子來處理它..我同意,我們可以添加觀察員在初始化..我想知道是否有任何我們可以避免在給該屬性設置一個值之前呼叫觀察者... – thecodejack

+0

不確定你在問什麼。觀察員的「工作」是在財產改變時得到通知。當然,如上例所示,您可以通過等待稍後創建它們來避免對觀察員的調用。一種變化是讓觀察者添加一些其他觀察者,並可能自己刪除。有了這個,你可以'避免'主要觀察者在初始設置的屬​​性。那是你要做的嗎? –

相關問題