Javascript 如何从Ember控制器访问查询参数
我正在做一件事。我从一系列习惯开始。当用户单击一个习惯时,它会为该习惯创建一个新事件。我的列表正在运行,但我在创建新事件时遇到了困难 要创建新事件,我有以下路线:Javascript 如何从Ember控制器访问查询参数,javascript,ember.js,scope,Javascript,Ember.js,Scope,我正在做一件事。我从一系列习惯开始。当用户单击一个习惯时,它会为该习惯创建一个新事件。我的列表正在运行,但我在创建新事件时遇到了困难 要创建新事件,我有以下路线: App.Router.map( function() { ⋮ this.resource( 'new_event', { path: '/event/new/:habit_id' } ) } ) 那么关联的路由器是: App.NewEventRoute = Ember.Route.extend( { model: fun
App.Router.map( function() {
⋮
this.resource( 'new_event', { path: '/event/new/:habit_id' } )
} )
那么关联的路由器是:
App.NewEventRoute = Ember.Route.extend( {
model: function(params) {
return this.store.find( 'habit', params.habit_id )
},
setupController: function( controller, model ) {
controller.set( 'selectedHabit', model )
}
} )
据我所知,唯一可以访问查询参数的地方是model函数
那么,控制器是:
App.NewEventController = Ember.ObjectController.extend( {
init: function() {
console.log( 'init', this.get( 'selectedHabit' ) )
// Logic for adding a new event for the habit
this.transitionToRoute( 'events' )
},
selectedHabit: null,
⋮
SelectedHabity的返回值为null。这实际上是有意义的,因为在调用setupController时,控制器作为参数传递,因此已经初始化。这意味着init函数已经被调用,SelectedHabity属性尚未设置 一种解决方案是创建一个通用函数来创建事件,也可以从其他地方调用该函数,以及使用所有观察SelectedHabity属性的逻辑
App.NewEventController = Ember.ObjectController.extend( {
/*passing an optional parameter of habitId, to make this generic, could be an option*/
addNewEvent:function(/*habitId*/){
// Logic for adding a new event for the habit
this.transitionToRoute( 'events' )
}.observes("selectedHabit"),
.
.
});
这是我的。我没有使用路线,而是采取了一项行动:
<script type="text/x-handlebars" id="habits">
<div id="habits">
{{#each}}
<div class="row" {{action 'createEvent' id}}>
<div class="col-xs-1 color" {{bind-attr style=style}}></div>
<div class="col-xs-8">{{name}}</div>
<div class="col-xs-3" data-role="timer">{{format-time-numeric lastTime}}</div>
</div>
{{/each}}
</div>
</script>
params.Habity_id是否返回您期望的值?是的。url的结尾被正确解析为id。
App.HabitsRoute = Ember.Route.extend( {
actions: {
createEvent: function( habitId ) {
var self = this
var store = this.get( 'store' )
store.find( 'habit', habitId ).then( function( habit ) {
store
.createRecord( 'event', {
habit: habit,
time: new Date()
} )
.save().then( function( event ) {
habit.get( 'events' ).then( function( events ) {
if( ! events ) {
events = []
habit.set( 'events', events )
}
events.pushObject( event )
habit.save().then( function() {
self.transitionTo( 'events' )
} )
} )
} )
} )
}
}
} )