2015-10-26 35 views
0

我在我的模板中有一個變量,名爲someString,我想在我的控制器中進行設置。我得到一個未捕獲的錯誤:斷言失敗:TypeError:無法讀取未定義的屬性'set'Ember:設置模板中的變量來自控制器

如何使控制器知道模板變量(如果這甚至是解決此問題的方法)?

我的模板看起來是這樣的:

{{#modal-dialog action="close" title="New Run"}} 
 
    <form role="form" {{action "submit" on="submit"}}> 
 
... 
 
    {{input value=emailComparisonRunID class="form-control" placeholder="Comparison Run ID (optional)"}} 
 
    <label><small>{{someString}}</small></label> 
 
    <br> 
 
... 
 
    </form> 
 
{{/modal-dialog}}

我的控制器看起來是這樣的:

export default Ember.ObjectController.extend({ 
 
    needs: 'services', 
 
    dataVer: '', 
 

 
    watchEmailComparisonRunId: function() { 
 
    var comparisonId = this.get('emailComparisonRunID'); 
 
    if(comparisonId == null) { 
 
     comparisonId = 1; 
 
    } 
 

 
    var onIdFound = function(id) { 
 
     console.log('FOUND'); 
 
     this.set('someString', 'FOUND'); 
 
    }; 
 

 
    var onIdNotFound = function(reason) { 
 
     console.log('Not Found'); 
 
     this.set('someString', 'NOT FOUND') 
 
    }; 
 

 
    this.get('store').find('run', comparisonId).then(onIdFound, onIdNotFound); 
 

 
    }.observes('emailComparisonRunID'), 
 
    
 
    ... 
 

 
    
 

+0

您可以通過在'this.set()'行上放置一個斷點並檢查'this'來調試。當你看到它等於'window'時,這將是一個很好的線索。順便說一句,打破了功能發現沒有找到,這是寫代碼,更多的人應該遵循的一個乾淨的方式表示祝賀。 – 2015-10-27 03:02:30

回答

0

你創造你的觀察者內部的函數被錯誤的上下文調用。更新它們以綁定其功能的上下文:

var onIdFound = function(id) { 
    console.log('FOUND'); 
    this.set('someString', 'FOUND'); 
}.bind(this); 

var onIdNotFound = function(reason) { 
    console.log('Not Found'); 
    this.set('someString', 'NOT FOUND') 
}.bind(this); 
+0

在這個時代箭頭的功能可能是一個更好的解決方案。 – 2015-10-27 03:00:49

+0

基於他使用'ObjectController',他是一個老版本的餘燼,早燼,CLI,因此不會與巴別塔。因此,我選擇了非常保險的回答(但是請注意,在我自己的項目,我會挑肥箭頭的答案)。 – Interrobang

相關問題