Ember.js setupController只触发一次

时间:2013-08-13 08:59:38

标签: javascript ember.js javascript-framework

假设我有一个观点:

CellarRails.SearchTextField = Ember.TextField.extend({
  templatename: 'index',
  insertNewline: function(){
    this.get('controller').set('query', this.get('value'));

    // calling search method of application controller
    this.get('controller').send('search');
    this.set('value', '');
  }
});

applicationController

CellarRails.ApplicationController = Ember.Controller.extend({
  needs: ['search'],
  query: '',

  // here is the search method
  search: function() {

    // I'm using ember-query lib, which provides this helper, it acts just like usual transitionToRoute
    this.transitionToRouteWithParams('search', {
      q: this.get('computedQuery')
    });
  },
  computedQuery: function() {
    this.get('controllers.search').set('q', this.get('query'));
    return this.get('query');
  }.property('query')
});

所以现在它应该转换为searchRoute

CellarRails.SearchRoute = Ember.Route.extend({
  serializeParams: function(controller) {
    return {
      q: controller.get('q')
    };
  },
  deserializeParams: function(params, controller) {
    controller.set('q', params.q);
  },

  // pass CellarRails.Track model to SearchController's context
  setupController: function(controller, context, params) {
    console.log('setup controller hooked!');
    controller.set('context', CellarRails.Track.find(params));
  }
});

CellarRails.Track模型中,我重新定义了find方法。 问题:此代码有效,但setupController仅在第一次(当我从applicationRoute过渡到searchRoute时)才会触发, BUT 如果我已经在searchRoute这个钩子没有触发,find模型的CellarRails.Track方法也不会触发。

3 个答案:

答案 0 :(得分:3)

在路线上设置setupController时,不会调用model挂钩。如果您希望同时触发modelsetupController两个挂钩,则必须在this._super(...)挂钩中调用setupController以维护model挂钩默认行为:

CellarRails.SearchRoute = Ember.Route.extend({
  ...
  model: function(params) {
    return CellarRails.MyModel.find();
  },
  setupController: function(controller, model) {
    this._super(controller, model);
    ...
  }
  ...
});

希望它有所帮助。

答案 1 :(得分:0)

尝试在SearchRoute中使用模型:hook

model: function ( params, transition ) {
    return CellarRails.Track.find(params);
}

如果你直接导航到url会调用它,希望所需的params将在params中但是尝试对它进行调试以检查:)

答案 2 :(得分:0)