Javascript 从嵌套函数访问外部对象(使用backbone.js
我正在使用backbone.js构建一个js重载应用程序。我遇到过几次的问题是如何从深度嵌套函数调用外部对象。在下面的代码示例中,我想在发生幻灯片事件时调用自定义函数事件。最好的方法是什么Javascript 从嵌套函数访问外部对象(使用backbone.js,javascript,backbone.js,Javascript,Backbone.js,我正在使用backbone.js构建一个js重载应用程序。我遇到过几次的问题是如何从深度嵌套函数调用外部对象。在下面的代码示例中,我想在发生幻灯片事件时调用自定义函数事件。最好的方法是什么 App.Views.Category = Backbone.View.extend({ ...., render: function () { $('#slider').slider({ min:0, max:100,
App.Views.Category = Backbone.View.extend({
....,
render: function () {
$('#slider').slider({
min:0,
max:100,
slide: function(event, ui) {
//HOW DO I CALL THE custom_function from here????
},
});
},
custom_function: function() {
alert('in custom function');
},
});
asdf有两种常见的选择 您可以将
this
放入像that
或self
这样的对象中,然后调用它
render: function () {
var that = this;
$('#slider').slider({
min:0,
max:100,
slide: function(event, ui) {
//HOW DO I CALL THE custom_function from here????
that.custom_function();
},
});
},
或者可以绑定函数的上下文
render: function () {
$('#slider').slider({
min:0,
max:100,
slide: (function(event, ui) {
//HOW DO I CALL THE custom_function from here????
this.custom_function();
}).bind(this),
});
},
Function.prototype.bind是ES5,因此只能用于跨浏览器支持我尝试了您以前使用的第一种方法。“this”将始终为我提供“#slider”dom元素,“that”将为空。对于第二种方法,我得到了“handlers.push-in-not Function”jquery出现错误。@DevX
.bind
仅在chrome/FF3.6+/IE9中有效,因此请在这些中尝试。您描述的内容听起来很奇怪。无论如何,我可能会使用x.bind来支持跨浏览器。在这种情况下,x.bind的语法是什么?@DevX您需要在第二个示例中的函数内部使用这个
,我修正了绑定(函数、范围)