嗨,伙计们!骨干 - 视图没有方法'得到'
我刚开始学习Backbone,我的第一个代码有问题。我做的示例代码中有一个按钮,一旦点击该按钮,就会添加一段代码(View),该代码应该从模型中获取一些默认值。但我收到一条消息:Object function(){return i.apply(this,arguments)} has no method 'get'
。这里是我的代码:
var app = {};
// the model
app.Answer = Backbone.Model.extend({
defaults: {
title: 'Your answer here',
isAnswer: false
}
});
//the collection
app.AnswerList = Backbone.Collection.extend({
model: app.Answer,
localStorage: new Store("backbone-answers")
});
//the view that is added when the button is clicked
app.AnswerView = Backbone.View.extend({
tagName: 'li',
// template: _.template($('#answer-template').html()),
template: _.template('<%= title %>: <%= isAnswer %>'),
events: {
'click button.destroy': 'remove',
},
initialize: function(){
_.bindAll(this, 'render','remove');
// this.model.bind('change', this.render());
this.render();
},
render: function(){
$(this.el).html(this.template({title: this.model.get('title'), isAnswer: this.model.get('isAnswer')}));
return this;
},
remove: function(){
$(this.el).destroy();
}
});
// the main view
app.AppView = Backbone.View.extend({
el: $('#body'),
events: {
'click button#insert-button': 'addAnswer'
},
initialize: function(){
_.bindAll(this, 'addAnswer');
this.ul = $('#content');
this.collection = new app.AnswerList();
console.log('initialize');
},
addAnswer: function(){
console.log('append');
var newAnswer = new app.AnswerView({model: app.Answer});
$('ul',this.el).append(newAnswer);
}
});
app.appView = new app.AppView();
我是Backbone的新手,所以我的问题是:我做错了什么?
感谢您的帮助!
传递给你的app.AnswerView实例模型应该是你app.Answer模型的实例,而不是在构造函数的引用。 – kinakuta
嗨@kinakuta,谢谢你的提示!你说,这部分:'var newAnswer = new app.AnswerView({model:app.Answer});',对吧?如果我只是把'var newAnswer = new app.AnswerView();',我得到这个错误:'不能调用未定义的方法'获取'。但是,如果我把'var newAnswer = new app.AnswerView({model:new app.Answer});',我没有错误,但视图不被追加。你知道为什么? –