【问题标题】:Can't access model attributes with Backbone.Marionette无法使用 Backbone.Marionette 访问模型属性
【发布时间】:2013-01-12 01:57:02
【问题描述】:

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

【问题讨论】:

  • 你真的可以在 ItemView 的初始化方法中 console.log 任何东西吗?
  • 是的,在每个 itemView 初始化方法中我都可以访问所有属性

标签: javascript backbone.js coffeescript marionette


【解决方案1】:

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

  // --- 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() 返回带有所有 '' 但没有的模板数据。 我不知道为什么。

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

【讨论】:

    猜你喜欢
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 2012-12-15
    • 2015-08-02
    • 2015-10-22
    • 1970-01-01
    相关资源
    最近更新 更多