繁体   English   中英

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

[英]Can't access model attributes with Backbone.Marionette

我在使用项目/复合视图访问模型属性时遇到了一些问题。 在我的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" }

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

  // --- 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

此解决方案对我有用。 对于我最初的问题,似乎是当我想重新获取模板原始文本时。 通常$('#usertemplate')。text()返回带有所有'<%= ...%>'但没有的模板数据。 我不知道为什么

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM