我不明白为什么当我在 this.model 上运行 this.model.fetch() 而不是在 view.render() 中时,它会在 view.intialize() 中定义。
define([
'jquery',
'underscore',
'backbone',
'text!templates/example.html'
], function($, _, Backbone, exampleTemplate){
var exampleView = Backbone.View.extend({
el: $('body'),
initialize: function() {
this.model.set({ _id: this.options.user_id });
this.model.fetch({
success: this.render,
error: function(model, response) {
console.log('ERROR FETCHING MODEL');
console.log(model);
console.log(response);
}
});
},
render: function() {
console.log('HELLO FROM RENDER');
console.log(this.model);
console.log('GOODBYE FROM RENDER');
}
});
return exampleView;
});
最佳答案
这是因为 this
的绑定(bind)不同,因为 render 被用作回调,将以下行作为 initialize
方法中的第一行来绑定(bind) this
到渲染方法的当前 View :
_.bindAll(this,"render");
Underscore.js bindAll function
Binds a number of methods on the object, specified by methodNames, to be run in the context of that object whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly useless this.
关于javascript - Backbone 模型未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8806835/