Muh*_*mbi 0 javascript jquery backbone.js underscore.js
我在骨干视图中有以下代码:
var BookView = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function() {
this.model.fetch({
success : function(model, resp, opt) {
alert(this.$el.html() ); //THIS ONE DOESN'T WORK?
}
});
alert(this.$el.html() ); // THIS ONE WORKS FINE
}
});
Run Code Online (Sandbox Code Playgroud)
我有两个alert(this.$el.html() );电话,一个在提取之外,一个在里面.但由于某种原因,fetch调用之外的那个工作,但fetch调用内的一个返回错误:
Uncaught TypeError: Cannot read property 'html' of undefined
在里面success,this不再是View(它是undefined在严格的模式,或window其他).
要解决这个问题,你可以使用常用的var that = this习语; 有关这个成语的更多信息,请参阅:'var that = this;' 用JavaScript表示?
var BookView = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function() {
var that = this; // define here
this.model.fetch({
success : function(model, resp, opt) {
alert(that.$el.html() ); // Use that instead of this here.
}
});
alert(this.$el.html() ); // THIS ONE WORKS FINE
}
});
Run Code Online (Sandbox Code Playgroud)
替代选项:请参阅.bind() - 一个体面的求助:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
render: function() {
this.model.fetch({
success : function(model, resp, opt) {
alert(that.$el.html() );
}.bind(this) // this.model.fetch.success now has bound 'this' permanently for any call to success from this method form here on out.
});
alert(this.$el.html() );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3954 次 |
| 最近记录: |