Ember中的“this”.js链接到助手

'this' in ember.js link-to helper

本文关键字:链接 js 中的 this Ember      更新时间:2023-09-26

我正在尝试获得流行ember.js框架的实践经验,并对许多神奇的东西感到非常惊讶。

其中之一是this link-to车把助手,我无法消化。

以下是我的代码方案:

// handlebar script
<script type='text/x-handlebars' data-template-name='products'>
  <h1>Products</h1>
  <ul class='list-unstyled col-md-8'>
    {{#each}}
      <h2>{{title}}</h2>
      <p>{{#link-to 'product' this class='btn btn-success' }}Buy for ${{price}}{{/link-to}}</p>
    {{/each}}
  </ul>
</script>
// in app.js    
App.PRODUCTS = [
  {
    title: 'Chair',
    price: 99,
    description: 'Chair is...',    
  },
  ...
];    
App.Router.map(function() {
  this.resource('products');
  this.resource('product', { path: '/products/:title'});  
});    
App.ProductsRoute = Ember.Route.extend({
  model: function() {
    return App.PRODUCTS;
  }
});
App.ProductRoute = Ember.Route.extend({
  model: function(params) {    
    return App.PRODUCTS.findBy('title', params.title);
  }
});

我知道this指的是模板中的current product,但我的问题是:

  1. 它是否与App.ProductRouterouter相互作用?如果是,如何?
  2. 我们可以用this.title代替this吗?
  1. 是的,link-to助手可以。link-to帮助程序会根据您提供的信息构建 URL。使用路由名称,它会查找路由器中定义的路由,并使用您指定的路径。然后,它使用来自对象的 ID 来填充动态段。如有必要,它还确保正确填写父路由。

  2. 不,您需要使用 this,因为它需要id来构建 URL。你以前只能this.id传球,但我认为你再也做不到了。(无论如何,这是一个坏主意。此外,Ember.js 将使用您传递的对象作为路由的模型,从而跳过ProductRoute中的model钩。你传递给它的对象可以是完全加载的模型,也可以是模型的承诺。