djm*_*ick 5 javascript backbone.js
我无法理解为什么this.model会在view.intialize()中定义,当我在它上面运行this.model.fetch()而不是在view.render()中.

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;
});
Run Code Online (Sandbox Code Playgroud)
这是因为this不同的绑定因为render被用作回调,所以将以下行作为方法的第一行initialize绑定this到render方法的当前视图:
_.bindAll(this,"render");
Run Code Online (Sandbox Code Playgroud)
在methodNames指定的对象上绑定许多方法,以便在调用它们时在该对象的上下文中运行.非常方便用于将用作事件处理程序的绑定函数,否则将使用相当无用的调用.