如何在d3.drag上下文中调用backbone.model

时间:2016-10-04 09:35:16

标签: javascript d3.js backbone.js

我有以下骨干模型和d3.drag功能。我无法在d3的上下文中调用模型的this

我通过定义变量model=this并按model.draw..调用来找到类似问题的解决方案但是如何在d3的拖动中添加它?

   DataMapper.Models.Anchor = Backbone.Model.extend({
                defaults: {
                        //...
                },
                initialize : function(){
                        d3.select("#anchor").call(this.dragAnchor); //make the #anchor draggable
                },
                dragAnchor: d3.drag()
                        .on("start", function (d) {
                            console.log("something"); //it prints
                            var thisDragY = this.drawSomething(a,b,c); 
                            // this.drawSomething is not a function
                            // because inside d3.drag(), 'this' refers to #anchor
                            // what I want to refer is the model
                        })
                        .on("drag", function (d) {})
                        .on("end", function (d) {}),
                drawSomething: function (parent, cx, cy) {
                   //code
                }
            });

有没有办法使用下划线的bind来达到我想要的目标? Link to a useful article

1 个答案:

答案 0 :(得分:0)

团队成员找到了解决方案 - 将拖拽称为函数。

   DataMapper.Models.Anchor = Backbone.Model.extend({
                defaults: {
                        //...
                },
                initialize : function(){
                        d3.select("#anchor").call(this.dragAnchor()); //make the #anchor draggable
                },
                dragAnchor: function(){
                        var self=this;
                        return d3.drag()
                           .on("start", function (d) {
                               console.log("something"); //it prints
                               var thisDragY = self.drawSomething(a,b,c); 
                           })
                           .on("drag", function (d) {})
                           .on("end", function (d) {}),
                drawSomething: function (parent, cx, cy) {
                   //code
                }
            });