【发布时间】:2015-11-30 19:43:36
【问题描述】:
我有一些模型,我想在更改时将 render 方法绑定到它。我正在尝试将 model.toJSON 传递给 render,但它不起作用。但是,如果我通过模型并在 render 中应用 toJSON,它会起作用。
(完整代码在这里:http://plnkr.co/edit/xoeY4hexnqgHnkxap5uj?p=preview)
window.onload=function(){
var defaultModel = Backbone.Model.extend({
defaults: {
greeting: 'Hello, Dude',
content: 'Coming soon...'
}
}),
defaultView = Backbone.View.extend({
tagName: 'section',
className: 'default',
initialize: function(option) {
this.template = $('#tmpl-default').html();
this.render();
var _this = this;
this.model.bind('change', _.bind(this.render, this, this.model.toJSON()));
$('[name="default-input"]').on('blur', function() {
console.log('got blurred....');
_this.model.set('content', this.value);
});
},
render: function(content) {
if (!content) {
console.log('%cno content', 'color: green');
content = this.model.toJSON();
}
this.$el.html(_.template(this.template)(content));
$('#content').html(this.$el);
return this;
}
}),
viewDefault = new defaultView({
model: new defaultModel()
});
};
上面的代码不起作用。如果我改变了
this.model.bind('change', _.bind(this.render, this, this.model.toJSON()));
到
this.model.bind('change', _.bind(this.render, this, this.model));
和
if (!content) {
content = this.model.toJSON();
}
到
if (!content) {
content = this.model.toJSON();
}else{
content = content.toJSON();
}
但是为什么呢?!
【问题讨论】:
-
想知道答案是否有帮助...?
标签: backbone.js model underscore.js bind render