我正在尝试从backbone render函数内的d3函数中引用backbone函数。我现在必须引用其他Backbone函数来做一些重要的事情,但是不能通过使用this/that方法来引用它们(我使用this/ƒthis):
define([
// this is for require.js file modularization
], function(){
return Backbone.View.extend({
initialize: function(options){
//CODE
this.render();
},
render: function(options){
// HOW I ACCESS THE BACKBONE VIEW IN NESTED SITUATIONS
var ƒthis = this;
//NORMAL RENDERING
if (!options) {
// Do some stuff, get some vars
// compile the template
// D3 stuff
var lineData = ({...});
var pathFunction = d3.svg.line()
var beatUnwindingPaths = [......];
var beatContainer = d3.select('#beatHolder'+this.parent.cid);
var beatPath = beatContainer //.append('g')
.insert('path', ':first-child')
.data([beatUnwindingPaths[0]])
.attr('d', pathFunction)
.attr('class', 'beat')
//THIS IS WHERE I WANT TO REFERENCE THE FUNCTION TO BE CALLED, AND HOW I THINK IT SHOULD BE CALLED
.on('click', ƒthis.toggle);
//BUT CURRENTLY I AM ONLY LIMITED TO CALLING A FUNCTION DECLARED WITHIN THE BACKBONE render func(), so it would look like this:
.on('click', toggle);
//CURRENTLY I AM HAVING TO DECLARE THE FUNCTIONS INSIDE RENDER
function unroll() {
//do some stuff
};
function reverse() {
};
$('#a').on('click', unroll);
$('#b').on('click', reverse);
}
},
// THIS IS THE FUNCTION I WANT TO CALL
toggle: function(){
//DO some stuff to the other BackBone models, collections and other cool stuff
}
});
});如何从D3代码内部访问主干toggle函数?
错误代码来自切换函数本身(以前工作过,所以我试图找出为什么现在不是),错误发生在313,而不是314,我的浏览器控制台总是离线。我放了一个console.log()来查看我在函数中获得的ƒthis.toggle,但是在布尔值的切换时出错。
311 toggle: function(){
312 //switch the selected boolean value on the model
313 this.model.set('selected', !this.model.get('selected'));
314 //re-render it, passing the clicked beat to render()
315 this.render(this.model);
316 // log.sendLog([[1, "beat" + this.model.cid + " toggled: "+!bool]]);
317 dispatch.trigger('beatClicked.event');
318 }我从在模板中渲染圆切换到让d3创建它(这样我们就可以使用d3函数对它进行动画处理),我想不知何故对象已经失去了它与模型的绑定。致力于此..。
发布于 2013-05-22 02:31:43
这不是D3/Backbone的问题,只是Javascript的问题。您不能传递一个稍后调用的对象方法,并期望this在该方法中工作,除非您以某种方式绑定它:
var myObject = {
method: function() {
this.doSomeStuff();
},
doSomeStuff: function() {
console.log("stuff!");
}
};
myObject.method(); // "stuff!"
// pass this method somewhere else - this is
// effectively what you do with an event handler
var myMethod = myObject.method;
myMethod(); // TypeError: Object [object global] has no method 'doSomeStuff'第二部分会失败,因为调用myObject.myMethod()将this绑定到myObject,但将方法分配给变量(或将其分配为事件处理程序)不会失败(在大多数情况下,this绑定到window,但D3会将this重新分配给您设置处理程序的DOM元素)。
标准的修复方法是: 1)将其封装在一个函数中:
var myMethod = function() {
myObject.method();
};
myMethod(); // "stuff!"或者2)以某种方式将其绑定到对象,例如在您的主干initialize方法中(下划线为此目的提供了一个有用的_.bindAll实用程序):
Backbone.View.extend({
initialize: function(options){
_.bindAll(this, 'toggle');
// now you can pass this.toggle around with impunity
},
// ...
});https://stackoverflow.com/questions/16672862
复制相似问题