我想要Ember.js'{{input value=“searchTerm”}}以将其值设置为''

I want Ember.js' {{input value="searchTerm"}} to set its value to ' ' when the URL changes

本文关键字:设置 js Ember input value 我想要 searchTerm      更新时间:2023-09-26

我会尽量简化这个问题,

但我需要我的handlebar.js‘{{input value="searchTerm"}}在每次URL更改时将searchTerm的值设置为"null"。

上面描述的输入旨在自动过滤同一页面上的列表。在输入中键入会自动将"searchTerm"的值更新为键入的

值searchTerm在名为searchResults 的操作中定义

这是控制器中的一个属性:

searchResults: function() {
    var searchTerm = this.get('searchTerm');
    var regExp = new RegExp(searchTerm, 'i');
    // We use `this.filter` because the contents of `this` is an array of objects
    var filteredResults = this.filter(function(category) {
        return regExp.test(category.get('categoryName'));
    });      
    return filteredResults;
}.property('@each.categoryName', 'searchTerm'),

所以要分解我需要的东西:

  1. 无论searchTerm的当前值是多少,都需要将其设置为"
  2. 只有在页面转换时才会将searchTerm的值设置为"

这可以通过didTransitionwillTransition事件处理程序在Route上完成。路由有一个对其controller的引用(通过this.controller),并且您仍然可以通过controllerFor获得它(例如:var c = this.controllerFor('controllerName');所以您可以这样做:

App.SomeRouteThatErasesTheSearchTermRoute = Ember.Route.extend({
  actions: {
    // you could implement with didTransition. No arguments for didTransition tho
    didTransition: function() {
      this.controller.set('searchTerm', '');  
    },
    // OR, implement with willTransition
    willTransition: function(transition) {
      this.controller.set('searchTerm', '');
    }
  }
});

您也可以将其实现为一个单独的方法,该方法将被激发on('willTransition'),因此您可以保留任何现有的处理程序,并只附加您的处理程序。然后,您可以将其制作为其他路由使用的mixin,或者其他路由可以从此类继承,而不破坏任何其他自定义转换处理程序(如果有的话)。