Backbone.js查看动态设置的标记名?

时间:2012-05-16 12:46:32

标签: javascript html backbone.js

我正在尝试使用jQueryMobile和Backbone.js为Phonegap项目设置基础架构
我们将针对多个平台,并计划在未来进行扩展 我希望我的Backbone代码完全不知道与Views关联的HTML元素的类型,因为我们不知道平台上的视图是什么样的。
一个简单的例子是,在一个平台上,项目列表可能来自ULLI元素,但是由于某种原因,我们可能希望将其切换为DIVP元素。

目前,如果我没有指定tagName,则默认为DIV 我希望能够在一个页面上提供这样的模板:

<script id="attachmentTemplate" type="text/template">
     <li><a href="#"><%= title %></a></li>
</script>

和另一个提供:

<script id="attachmentTemplate" type="text/template">
    <p><a href="#"><%= title %></a></p>
</script>

如果没有指定tagName,我就不能这样做(正如我所说,默认为DIV)。

有没有人有任何建议或方法可以做到这一点?关键是我不希望Javascript知道HTML元素的类型,我希望HTML能够定义它。

3 个答案:

答案 0 :(得分:13)

您可以在视图中使用函数指定tagName属性,因此它将是动态的。

...

tagName: function(){
    return this.model.get('tagName');
},

...

查看此小提琴http://jsfiddle.net/b7mR6/

答案 1 :(得分:4)

虽然我不推荐这种架构,但您可以覆盖渲染方法:

render: function() 
{
    // unbind all handlers since delegateEvents was called in the constructor
    this.undelegateEvents();
    // set this.el to the domElement from the templates
    this.el = this.template(this.model.toJSON()); // or however you get to your template
    // create the shorthand dom reference that setElement() creates
    this.$el = $(this.el);
    // re-delegate the events
    this.delegateEvents();
}

这意味着您无需担心在模板中定义的tagName。

编辑:查看Backbone代码,这正是setElement所做的,所以理论上你可以试试

render: function() 
{
    var tpl = this.template(this.model.toJSON());
    this.setElement(tpl, true);
    return this;
}

答案 2 :(得分:1)

像往常一样,我搜索并搜索并找不到答案,然后我问一个问题并自己弄清楚。

我发现如果我像这样制作模板:

<script id="attachmentTemplate" tagname="li" type="text/template">
    <a href="#"><%= title %></a>
</script>

然后在我的js代码中,在实例化我的View时我可以这样做:
var attachmentView = new AttachmentListItemView({ tagName: $('#attachmentTemplate').attr('tagname'), model: item });

它完美无缺 不知道这是否是有效的HTML或者会导致任何问题。