我正在使用木偶来渲染我的观点和模板。
除了将集合传递到我的视图之外,我还需要在模板中显示其他自定义变量,例如'昵称'如下所示
我目前只将一个集合传递给我的'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"
答案 0 :(得分: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