我有一个Backbone视图,它绑定到 notes 集合的 add 事件,如下所示(使用CoffeeScript):
initialize: () ->
@options.notes.bind('add', @noteAdded)
这里是 noteAdded 方法以及 addOneNote 方法,该方法被调用以将最近创建的注释添加到DOM:
addOneNote: (note) =>
view = new CrmBliss.Views.Consultants.NoteView({model: note})
@$(".past_notes").prepend view.render().el
noteAdded: (model, response) =>
console.debug 'model', model.toJSON()
@addOneNote(model)
最后,这是我如何在集合上调用 create 方法:
saveNote: (e) =>
id = @model.get('id')
body = @$('.note-body').val()
@options.notes.create({ body: body, consultant_id: id })
我预计会使用反映数据库中添加内容的模型调用 noteAdded 。为模型返回了一些字段,这些字段不是由客户端插入的,而是由服务器计算的。也就是说, created_at 和 user_name 是服务器返回的方法,但客户端在从服务器获取之前不知道。
所以当我尝试渲染以下(eco)模板时:
<div class="note">
<span class="date"><%= @created_at %></span>
by
<span class="taker"><%= @user_name %></span>
<div class="note_body">
<%= @body %>
</div>
</div>
仅渲染正文(因为用于创建注释的对象已具有body属性)。
如果我在插入注释之前将 noteAdded 方法更改为等待一段时间,则可以正常工作:
noteAdded: (model, response) =>
console.debug 'note before', model.toJSON()
console.debug 'model', model
attrShow = =>
console.debug 'after time', model.toJSON()
@addOneNote(model)
setTimeout(attrShow, 1000)
这使得我明显地绑定到错误的事件,并且我应该绑定到从服务器加载模型时调用的事件。
我应该绑定哪个事件,在调用时,它具有正确的(和最终的)模型属性?