控制器上的绑定值

时间:2014-12-25 16:40:26

标签: ember.js binding

我有两个控制器,SidebarCategoriesControllerMainLinksController。我在selectedCategory上有一个属性SidebarCategoriesController,而MainLinksController在呈现模板时需要此属性。

App.MainLinksController = Ember.ObjectController.extend({
     needs: "sidebarCategories"
});

App.SidebarCategoriesController = Ember.ObjectController.extend({
    selectedCategory:2,
    actions: {
        setCategory: function (id){
            this.set('selectedCategory',id);
        }
    }
});

我还有一个模板(下面),其控制器是MainLinksController:

<script  type="text/x-handlebars" data-template-name="main_links">
 <h2 class="panel-title">All links:{{controllers.sidebarCategories.selectedCategory}}</h2>
</script>

问题是,在selectedCategory中更新SidebarCategoriesController时,selectedCategory通过MainLinksController使用{{controllers.sidebarCategories.selectedCategory}}的模板未获得更新。如何进行绑定,以便selectedCategory中的SidebarCategoriesController更改,{{controllers.sidebarCategories.selectedCategory}}也会在模板中发生更改?

1 个答案:

答案 0 :(得分:1)

我修改了你的jsbin以使其工作如下:

App.CategoryManagerController = Ember.Controller.extend({
  selectedCategory: 5
});

App.SidebarCategoriesController = Ember.ObjectController.extend({
    needs: ['categoryManager'],
    selectedCategory: Ember.computed.alias('controllers.categoryManager.selectedCategory'),
    actions: {
        setCategory: function (){
            this.set('selectedCategory', 3);
        }
    }
});

App.MainLinksController = Ember.ObjectController.extend({
    needs: ['categoryManager'],
    selectedCategory: Ember.computed.alias('controllers.categoryManager.selectedCategory')
});

完整的解决方案here