【问题标题】:'this' in ember.js link-to helperember.js 中的“this”链接到帮助程序
【发布时间】:2014-04-06 06:29:28
【问题描述】:

我正在尝试亲身体验流行的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 吗?

【问题讨论】:

    标签: javascript ember.js handlebars.js


    【解决方案1】:
    1. 是的,link-to 助手可以。 link-to 帮助程序根据您提供的信息构建一个 URL。使用路由名称,它会查找在您的路由器中定义的路由并使用您指定的路径。然后它使用来自对象的 ID 来填充动态段。它还确保在必要时正确填写父路由。

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

    【讨论】:

    • 它是在我的情况下特别搜索'id'还是使用'title'来填写动态段,因为我定义的路线是'/products/:title'?
    • 我没有看到您将title 作为动态细分。 Ember.js 总是将 ID 放在路由的动态段中。如果您想在其中放置其他内容,则必须将其设置为模型的 ID。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 2012-02-05
    • 1970-01-01
    • 2011-01-01
    • 2018-01-21
    • 1970-01-01
    相关资源
    最近更新 更多