[英]ember.js transition to route from within child view & controller
我有一個從路線自動渲染的模板。 車把模板指定子視圖。
子視圖在我的js中有一個擴展View,它指定了一個要使用的控制器。 它還有一個引發事件的點擊處理程序。 控制器處理事件。
到目前為止這是有效的 - 問題是控制器試圖調用...
this.transitionToRoute("about")
由於某些原因,這是行不通的。
我還在主視圖上處理一個click事件,並在它的控制器中使用完全相同的方法,並且可以工作。 那么區別是什么呢? 我可以做些什么來處理過渡?
示例: http : //jsfiddle.net/b6xsk/4/
在示例中,您可以看到索引上的單擊有效,而單擊子視圖則沒有。
下面的代碼與小提琴相匹配。
我的模板......
<script type="text/x-handlebars">
{{#linkTo "index"}}Index{{/linkTo}}
{{#linkTo "about"}}About{{/linkTo}}
<div class="app-template">
{{outlet}}
</div>
</script>
<script type="text/x-handlebars" data-template-name="index">
<h1>Index (click me)</h1>
{{view App.ChildView}}
</script>
<script type="text/x-handlebars" data-template-name="about">
<h1>About</h1>
</script>
<script type="text/x-handlebars" data-template-name="childview">
<h2>Child View (click me)</h2>
</script>
然后是我的JS ......
App = Ember.Application.create();
// two simple routes
App.Router.map(function() {
this.route("index");
this.route("about");
});
// index controller handles event and moves to about route
App.IndexController = Ember.Controller.extend({
useraction: function(event) {
console.log("User Action");
this.transitionToRoute("about"); // works !
}
});
// index view handles the click and raises event (handled by controller)
App.IndexView = Ember.View.extend({
click: function(event) {
this.get('controller').send('useraction', event);
}
});
// handles child event and tries (but fails) to transition to about route
App.ChildViewController = Ember.Controller.extend({
childuseraction: function(event) {
console.log("Child User Action");
// do some validation or other code and maybe then transition
// in this example always transition
this.transitionToRoute("about"); // doesn't work ! why??
event.stopPropagation(); // don't allow the event to bubble
}
});
// instantiated so we can attach to view below
App.childViewController = App.ChildViewController.create();
// child view is added in the index handlebar template and raises
// event on click that is handled by child view controller
App.ChildView = Ember.View.extend({
templateName: 'childview',
controller: App.childViewController,
click: function(event) {
this.get('controller').send('childuseraction', event);
}
});
不同的是indexController有一個對應用程序路由器的引用,但是你創建的childViewController沒有對所述路由器的引用。 你應該讓Ember為你創建控制器,你可以這樣做。
在ChildView中刪除childController創建和控制器規范。
將以下內容添加到IndexController
needs: ['childView'] // Can be a string if you only need one other controller
這將使Ember為您創建控制器,並將其添加到indexController的控制器集合中。 然后,您可以在索引模板中指定controllerBinding
,如下所示。
{{view App.ChildView controllerBinding="controllers.childView"}}
更詳細的解釋可以在這里找到管理控制器之間的依賴關系和這里darthdeus與Ember.js:控制器的需求解釋
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.