【发布时间】:2011-08-16 14:37:37
【问题描述】:
我有一个显示几个输入字段的视图设置。当任一字段发生更改时,我想保存模型的更改值。
这是我的看法:
EditWordView = Backbone.View.extend({
tagName: 'article',
className: 'word',
initialize: () ->
_.bindAll this, 'render'
this.template = _.template($('#edit-word-template').html())
this.model.bind 'change', this.render
,
events: {
"change input": "changed"
},
render: () ->
this.model.fetch()
$word = $('#word')
$word.empty()
renderContent = this.template(this.model.toJSON())
$(this.el).html(renderContent)
$word.append(this.el)
this
,
changed: (event) ->
changed = event.currentTarget
value = $("#" + changed.id).val()
obj = {}
obj[changed.id] = value
this.model.save(obj)
,
save: (event) ->
this.model.save()
view = new WordView({model: this.model})
view.render()
event.preventDefault()
})
这是模型:
SpellingWord = Backbone.Model.extend({
url: () ->
'/spelling_words/' + this.id
})
当我到达更改的事件并尝试保存模型时
this.model.save(obj)
没有效果
set(attrs) 方法在主干.js 中的 save 方法中在模型上调用,但模型中的值永远不会改变,因此永远不会持久化回后端。这与 this.model 对象的范围有关吗?
如果我打电话
this.model.set(obj)
在 this.model.save(obj) 之前,模型的属性值永远不会改变。
set(attrs) 在控制台中为对象工作,所以我有点困惑为什么它不会在我看来。
想法?
编辑>>>>>>>
我已经深入研究了主干代码并在 save 方法中调用了 set:
save : function(attrs, options) {
options || (options = {});
if (attrs && !this.set(attrs, options)) return false;
var model = this;
var success = options.success;
在 this.set(attrs, options) 方法被调用后,模型的属性没有改变。
现在,查看 set 方法,我看不到在实际更改 now 变量时应该如何更改属性?
var now = this.attributes, escaped = this._escapedAttributes;
// Run validation.
if (!options.silent && this.validate && !this._performValidation(attrs, options)) return false;
// Check for changes of `id`.
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
// We're about to start triggering change events.
var alreadyChanging = this._changing;
this._changing = true;
// Update attributes.
for (var attr in attrs) {
var val = attrs[attr];
if (!_.isEqual(now[attr], val)) {
now[attr] = val;
delete escaped[attr];
this._changed = true;
if (!options.silent) this.trigger('change:' + attr, this, val, options);
}
}
【问题讨论】:
标签: backbone.js