本文介绍了骨干网 - 更改标签名条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图切换基于条件的骨干视图的标记名。

I'm trying to switch the tagName of a Backbone view based on a condition.

我最初以为我将能够设置说'格'(我意识到这是默认设置),然后在视图的初始化函数的默认记名,检查条件和更改标记名,但这可惜没的工作。

I initially thought I would be able to set a default tagName of say 'div' (I realize this is the default), then in the view's initialize function, check for the condition and change the tagName but this unfortunately didn't work.

下面是我的看法code(写在CoffeeScript中):

Here is my view code (written in coffeescript):

  class Test.Views.ListView extends Backbone.View
    attributes: {"data-role": "listview"}
    className: 'row'
    tagName: 'div'
    initialize: ->
      if @options and @options.device == "mobile"
        @template = "/app/templates/mobile/test/test.html"
        @tagName = 'ul'

有了这个code,标记名没有变化,它始终保持一个div。当模板正确切换。

With this code, the tagName does not change, it always remains a div. While the template is switched correctly.

任何帮助将是AP preciated。干杯!

Any help would be appreciated. Cheers!

推荐答案

视图的设置初始化被调用。从:

view.el

所有的观点在任何时候都DOM元素(在属性)...

All views have a DOM element at all times (the el property)...

因此​​,所有视图实例始终有一个,特别是从视图的<$ C创建$ C>标签名在初始化被调用。你试图改变 @tagName 在你的构造函数,但已经存在所以它是为时已晚,一个简单的 @tagName 更改有任何效果。

So all view instances always have an el and in particular, el is created from the view's tagName before initialize is called. You're trying to change @tagName in your constructor but el already exists so it is too late for a simple @tagName change to have any effect.

您可以使用来改变视图的

setElement view.setElement(元素)

如果你想一个骨干视图适用于不同的DOM元素,使用 setElement ,这也将创造缓存 $ EL 参考和移动从旧元素视图的委派事件到新的。

If you'd like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached $el reference and move the view's delegated events from the old element to the new one.

事情是这样的:

initialize: ->
  if @options and @options.device == "mobile"
    @template = "/app/templates/mobile/test/test.html"
    @setElement(@make('ul', _(@attributes).extend(class: @className)))

您还可以设置 @tagName ='UL',如果你想,但它不会重要,因为标签名只是实例化一个视图时使用。此外, @options 应该永远存在,所以你不必检查,并由于您使用的CoffeeScript的的会,如果你想反正要检查它是更地道:

You could also set @tagName = 'ul' if you wanted but it won't matter since tagName is only used when instantiating a view. Also, @options should always be there so you don't have to check it and since you're using CoffeeScript, the accessor variant of the existential operator would be more idiomatic if you wanted to check it anyway:

if @options.?device == 'mobile'

演示:

这篇关于骨干网 - 更改标签名条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 15:01