无法使用Backbone.Marionette访问模型属性

时间:2013-01-28 16:49:42

标签: javascript backbone.js coffeescript marionette

我对使用item / composite视图的模型属性访问有一点问题。 在我的ItemView中,我有所有模型属性数据,但是当我想要在我的html /模板中输出<%=username%>时没有。

我不知道为什么这不起作用。通常代码就像我的一样简单。

要点:https://gist.github.com/e6e68b525468606bd039或以下:

的index.html:

<section>
  <%= test %>
  <ul class="thumbnails" id='userslist'></ul>
</section>

<script type="text/template" id="usertemplate">
  Username: <%= username %>
</script>

test.coffee:

define [ 'jquery', 'underscore', 'backbone', 'marionette', 'text!templates/us/index.html' ], ( $, _, Backbone, Marionette, TPL) ->

    class UserView extends Backbone.Marionette.ItemView
        template  : '#usertemplate'
        tagName   : 'li'
        className : 'span2'

        initialize: ->
            console.log 'm:', @model.attributes

    class UsPageView extends Backbone.Marionette.CompositeView
        template : _.template TPL
        itemView : UserView

        itemViewContainer: "#userslist"

        initialize: (options) ->
            @collection = options.collection
            @collection.fetch()

        appendHtml: (cView, iView, idx) ->
            cView.$(@itemViewContainer).append iView.el

        serializeData: ->
            test: 'ok'

    UsPageView

console.log打印:Object { username: "Foo" }

1 个答案:

答案 0 :(得分:0)

我找到了一个临时解决方案: - 我使用模板代码创建了一个新文件:

  // --- members.html
  Username: <%= username %>

我改变了我的ItemView类:

define [ 'jquery', 'underscore', 'backbone', 'marionette', 'text!templates/us/index.html', 'text!templates/us/members.html' ], ( $, _, Backbone, Marionette, TPL, M) ->

    class UserView extends Backbone.Marionette.ItemView
        tagName   : 'li'
        className : 'span2'

        template: (serializedModel) =>
            _.template M, @model.toJSON()

    class UsPageView extends Backbone.Marionette.CompositeView
        template          : _.template TPL
        itemView          : UserView    
        itemViewContainer : "#userslist"

        initialize: (options) ->
            @collection = options.collection
            @collection.fetch()

        appendHtml: (cView, iView, idx) ->
            cView.$(@itemViewContainer).append iView.el

    UsPageView

此解决方案适合我。 对于我最初的问题,似乎是我想要重新使用我的模板原始文本。 Normaly $('#usertemplate')。text()返回所有'&lt;%= ...%&gt;'的模板数据但不是。 我不知道为什么。

如果有人找到我仍然感兴趣的解决方案:)

相关问题