2014-10-01 91 views
0

我試圖在窗體輸入旁邊顯示錯誤。在目前的版本中,只要控制器中的fooErrors屬性發生變化,它就會重新渲染頁面。然而,它將整個視圖都渲染出來,從而使視圖中的標題混亂起來。有沒有辦法我只能重新渲染包含組件的視圖部分?Emberjs只有在觸發觀察者後才重新渲染組件

的代碼:

應用/視圖/富/ form.js:

export default Ember.View.extend({ 
    errorsChanged: function() { 
    this.rerender(); 
    }.observes('controller.fooErrors') 
}); 

應用程序/控制器/富/ edit.js:

export default Ember.ObjectController.extend(Ember.Validations.Mixin,{ 
    fooErrors: false, 
    actions: { 
    submit: function() { 
     var _this = this; 
     var foo = this.get('content'); 
     foo.validate().finally(function() { 
     // form is submitted 
     } else { 
      foo.set('hasErrors', true); 
      _this.set('fooErrors', true); 
     } 
     }); 
    } 
    } 
}); 

應用/模型/富.js:

export default DS.Model.extend(Ember.Validations.Mixin, { 
    hasErrors: false 
} 

app/foo/form.hbs

<h1>{{fooId}}</h1> 
<form> 
{{input type="text" placeholder="foo id" valueBinding="fooId"}}{{form-error errors=fooErrors foo=model field="fooId"}} 
<button {{action 'submit'}}>Submit</button> 
</form> 

應用/模板/組件/形式error.hbs:

{{#if errors}} 
    <span>{{error}}</span> 
{{/if}} 

應用程序/組件/形式error.js:

export default Ember.Component.extend({ 
    tagName: 'span', 
    classNames: ['error'], 
    error: function() { 
    var risk = this.risk, 
     field = this.field; 

    if (risk.get('hasErrors')) { 
     return risk.get('errors').get(field); 
    } else { 
     return ''; 
    } 
    }.property() 
}); 
+0

爲什麼你要重新呈現該組件? – saygun 2014-10-02 00:47:01

回答

0

繼OP設計,一個簡單的刷新組件的方法是從視圖中獲取它並調用rerender。要從視圖中獲取組件,只需添加一個viewName

例如,

HBS

....{{form-error errors=fooErrors foo=model field="fooId" viewName="theErrorsCmp"}} 

JS

export default Ember.View.extend({ 
    errorsChanged: function() { 
//if this fires for some reason at the very beginning before the view has been inserted to the DOM and the component is not yet available then just check before using it, i.e. uncomment the following line 
//if(!Em.isEmpty(this.get("theErrorsCmp"))) 
    this.get("theErrorsCmp").rerender(); 
    }.observes('controller.fooErrors') 
}); 
相關問題