动态ID骨干视图 [英] backbone view with dynamic id

查看:125
本文介绍了动态ID骨干视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我才意识到我被误解了 Backbone.View 属性。基本上我的观点需要动态 ID 属性基于其模型的属性。我觉得我有这个工作很好,因为我只是在我的模板中指定的:

I just realized I was misunderstanding the el attribute of a Backbone.View. Basically my views require dynamic id attributes based on its model's attribute. I thought I had this working fine because I simply specified it in my template:

<script type="text/template" id="item_template">
  <li class="item" id="{{identifier}}">
    <span class="name">{{name}}</span>
  </li>
</script>

不过,我意识到,实际上是做什么的主力,是把这个编译模板到另一个元素, DIV 默认情况下。我更多地了解了这个通过阅读文件,但我仍然困惑如何创建一个动态 ID

However, I realized that what Backbone was actually doing was putting this compiled template into another element, div by default. I learned more about this by reading the documentation, but I'm still confused on how to create a dynamic id.

preferably,我很想找到一种方法,使其使得在上面的模板的东西,作为我的,因为它已经拥有的一切,我想要的,但我不知道这是否是可能的。所以我想,如果很简单,有指定一个动态的方式 ID 属性。

Preferably, I would love to find a way to make it such that the stuff in the above template serves as my el, since it already has everything I want, but I don't know if that is possible. So I'm wondering if, quite simply, there is a way to specify a dynamic id attribute.

我试过在初始化方法 this.id = this.model.get('ATTR')但它似乎没有任何效果,可能是因为这时候已经是太迟了。

I tried setting it within the initialize method, this.id = this.model.get('attr') but it didn't seem to have any effect, possibly because by this time it is already too late.

什么我目前做的只是使用jQuery添加 ID 在期间渲染()

What I'm currently doing is just using jQuery to add the id in during render():

this.el.attr(id: this.model.get('identifier'));

它的工作原理,但当然,我只是问,如果有一个preferred方式,通过骨干做到这一点。

it works, but of course, I'm simply asking if there is a preferred way to do it through Backbone.

推荐答案

是的,有在骨干做到这一点的标准方式。你可以通过 ID 来查看构造函数。您也可以重构你的模板,以便创建骨干父&LT;立GT; 元素为您服务。试试这个简单的模板:

Yes there is a standard way to do this in Backbone. You can pass id to the View constructor. You can also refactor your template so that Backbone creates the parent <li> element for you. Try this simpler template:

<script type="text/template" id="item_template">
  <span class="name">{{name}}</span>
</script>

和这些添加到您的视图:

And add these to your view:

myView = Backbone.View.extend({
  className: "item",
  tagName: "li"
})

和实例化它是这样的:

var view = new YourView({
  model: mymodel,
  id: mymodel.get('identifier') // or whatever
})

祝你好运!

这篇关于动态ID骨干视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆