2

我正在使用木偶来渲染我的视图和模板。

除了将集合传递给我的视图之外,我还需要在模板中显示其他自定义变量,例如“昵称”,如下所示

我目前只将一个集合传递给我的“message_view”。我如何也可以为“昵称”传递自定义变量?

//template JST["backbone/templates/messages/index"]
.message_wrapper
  .title
    //NEED TO DISPLAY NICKNAME here
    %h4 Chat with <%= nickname %>
  %ul.messages
    %li.message.load_more_messages 

视图和控制器设置如下:

List.Controller =
  listMessages: (nickname) ->
    messages = new Onethingaday.Collections.MessagesCollection()
    messages.url = "/v1/messages/#{nickname}.json"

    messages.remoteGet
      success: (collection, response) =>
        //ONLY PASSING IN COLLECTION TO MESSAGE VIEW, NEED VARIABLE NICKNAME AS WELL
        messages_view = new List.Messages
          collection: collection

        @layout.messagesRegion.show(messages_view)

class List.Message extends Marionette.ItemView
  template: JST["backbone/templates/messages/message"]
  className: 'message'
  tagName: 'li'

class List.Messages extends Marionette.CompositeView
  template: JST["backbone/templates/messages/index"]
  itemView: List.Message
  itemViewContainer: "ul.messages"
4

1 回答 1

2

您可以使您的收藏 url 属性成为一个函数,并使用解析将昵称映射到您的收藏。

Onethingaday.Collections.MessagesCollection = Backbone.Collection.extend({
  initialize: function(){
    this._nickname = "a_sane_default";
  },
  setNickname : function(nickname) {
    this._nickname = setValue;
  }
  url: function(){
    return "/v1/messages/" + this._nickname + ".json";
  },
  parse: function(res) {
    var self = this;
    return _.map(res, function(source) {
      obj = _.clone(source);
      obj.nickname = self._nickname;
      return obj;
    }
  }
 });

(咖啡)

class Onethingaday.Collections.MessagesCollection extends Backbone.Collection
  initialize: -> 
    @_nickName = "a_sane_default"
  setNickname: (nickname) -> 
    @_nickName = nickname
  url: ->
    return "/v1/messages/#{@_nickname}.json"
  parse: (res) ->
    return res.map (source) =>
      obj = _.clone(source)
      obj.nickname = @_nickname
      return obj
于 2013-04-22T11:55:56.143 回答