草庐IT

javascript - 不寻常的 d3 放大可重用类 - this 和 bind

coder 2025-01-12 原文

一段时间以来,我一直在为这个问题绞尽脑汁......

我在 js 中有一个常用的构造函数/原型(prototype)对象(如类),它包含我所有的 d3 图表逻辑:

figureGen = function(html_element) {
  this.svg = d3.select(html_element)
    .append('svg')
    .style('width', '100%')
    .style('height', '100%')
    .append('g')
      .attr("class", "sadrzalac")
      .attr("transform", "translate(" + 0 + "," + 0 + ")");
      this.element = element;
      this.data = [];
      this.yRange = d3.scale.linear();
      this.xRange = d3.scale.linear();
      this.xAxis = undefined;
      this.yAxis = undefined;
      this.width = undefined;
      this.height = undefined;
      this.zoom = undefined;
      this.margin = {top: 20, right: 20, bottom: 20, left: 35};
      this.svg.append("rect") 
       .attr("class", "clipPath")
       .attr("transform", "translate(" + this.margin.left + "," + -this.margin.top + ")");
      this.svg.append('g')
       .attr("class","xaxis axis");
      this.svg.append('g')
      .attr("class", "yaxis axis");
}

对于构造函数,对于像这样的方法

figureGen.prototype = {
    constructor: figureGen,
    init: function(sampledata, width, height){
       var y_min = Number(d3.min(this.podaci, function (d) { return d.y;})); 
       var y_max = Number(d3.max(this.podaci, function (d) { return d.y;}));
       var x_min = Number(d3.min(this.podaci, function (d) { return d.x;}));
       var x_max = Number(d3.max(this.podaci, function (d) { return d.x;}));

       var ukupan_opseg = y_max - y_min;
       var spacer = (ukupan_opseg*25)/100;

       this.xRange = d3.scale.linear().range([this.margin.left + 10, this.width - this.margin.right]).domain([x_min, x_max]);
       this.yRange = d3.scale.linear().range([this.height - this.margin.top, this.margin.bottom]).domain([y_min-spacer, y_max+spacer]);

      this.zoom = d3.behavior.zoom()
        .x(this.xRange)
        .y(this.yRange)
        .scaleExtent([1, 5])
        .center([this.width / 2, this.height / 2])
        .size([this.width, this.height])
        .on("zoom", this.zoomProcess());

       this.svg
        .attr("width", this.sirina)
        .attr("height", this.visina)
        .call(this.zoom);

        this.xAxis = d3.svg.axis()
           .scale(this.xRange)
           .innerTickSize(-this.height+40)
           .outerTickSize(5)
           .tickPadding(10)
           .tickFormat(d3.format("d"));

        this.yAxis = d3.svg.axis()
           .scale(this.yRange)
           .orient("left")
           .innerTickSize(-this.width)
           .outerTickSize(5)
           .tickPadding(10)
           .tickSubdivide(false);

       this.svg.select('.xosa')
           .attr("transform", "translate(0," + (this.height - this.margin.bottom) + ")")
           .call(this.xAxis);

       this.svg.select(".yosa")
           .attr("transform", "translate(" + (this.margin.left) + ",0)")
           .call(this.yAxis);
  },
  zoomProcess: function{
      this.svg.select(".xaxis").call(this.xAxis);
      this.svg.select(".yaxis").call(this.yAxis);
      console.log(this.svg);
  }
}

问题出在 zoomProcess 方法中,它总是返回(记录)this.svg 上的 HTML 元素,而不是可以 .select 的 this.svg 对象。缩放行为已正确附加到我的元素,并且在鼠标 whell 上开始缩放,但它弹出一个错误,指出无法执行 this.xAxis 上的此 .call。

当我从另一个来源触发 zoomProcess 时,更奇怪的是,就像单击按钮一样,其控制台日志输出正确的 this.svg 对象而不是 HTML 元素,因此错误似乎来自缩放事件处理程序。这里有什么问题吗?

这是我一直在看的两个例子:
http://bl.ocks.org/stepheneb/1182434
http://bl.ocks.org/mbostock/7ec977c95910dd026812

编辑: 现在我想我可能应该在 this 对象上使用 .bind() 以便在转到 zoomProcedura 方法时它的引用保持不变。我仍然不确定该怎么做。

最佳答案

我假设您的实际代码中没有错字...

  zoomProcess: function{
      this.svg.select(".xaxis").call(this.xAxis);
      this.svg.select(".yaxis").call(this.yAxis);
      console.log(this.svg);
  }  

大概是……

  zoomProcess: function(){
      this.svg.select(".xaxis").call(this.xAxis);
      this.svg.select(".yaxis").call(this.yAxis);
      console.log(this.svg);
  }

或者也许……

  zoomProcess: function(){
      return function() {
          this.svg.select(".xaxis").call(this.xAxis);
          this.svg.select(".yaxis").call(this.yAxis);
          console.log(this.svg);
      }
  }

我不能确定。 而且我假设您确实正在调用...

    .on("zoom", this.zoomProcess());

不是...

    .on("zoom", this.zoomProcess);

但是无论如何,基于这个假设,要让它按照您想要的方式工作,请尝试...

  zoomProcess: function(){
      //'this' is figureGen.prototype
      var that = this;
      return function () {
          //'this' is window
          that.svg.select(".xaxis").call(that.xAxis);
          that.svg.select(".yaxis").call(that.yAxis);
          console.log(that.svg);
      }
  }  

或者……

  zoomProcess: function(){
      //'this' is figureGen.prototype
      return function () {
          //'this' is figureGen.prototype
          this.svg.select(".xaxis").call(this.xAxis);
          this.svg.select(".yaxis").call(this.yAxis);
          console.log(this.svg);
      }.bind(this)
  }

关于javascript - 不寻常的 d3 放大可重用类 - this 和 bind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31208480/

有关javascript - 不寻常的 d3 放大可重用类 - this 和 bind的更多相关文章

  1. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

  2. ruby-on-rails - 创建 ruby​​ 数据库时惰性符号绑定(bind)失败 - 2

    我正在尝试在Rails上安装ruby​​,到目前为止一切都已安装,但是当我尝试使用rakedb:create创建数据库时,我收到一个奇怪的错误:dyld:lazysymbolbindingfailed:Symbolnotfound:_mysql_get_client_infoReferencedfrom:/Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundleExpectedin:flatnamespacedyld:Symbolnotfound:_mysql_get_client_infoReferencedf

  3. ruby-on-rails - 使用 javascript 更改数据方法不会更改 ajax 调用用户的什么方法? - 2

    我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的

  4. ruby - 你会如何在 Ruby 中表达成语 "with this object, if it exists, do this"? - 2

    在Ruby(尤其是Rails)中,您经常需要检查某物是否存在,然后对其执行操作,例如:if@objects.any?puts"Wehavetheseobjects:"@objects.each{|o|puts"hello:#{o}"end这是最短的,一切都很好,但是如果你有@objects.some_association.something.hit_database.process而不是@objects呢?我将不得不在if表达式中重复两次,如果我不知道实现细节并且方法调用很昂贵怎么办?显而易见的选择是创建一个变量,然后测试它,然后处理它,但是你必须想出一个变量名(呃),它也会在内存中

  5. ruby-on-rails - Rails - Carrierwave 进程抛出 ArgumentError : no images in this image list - 2

    在尝试实现应用auto_orient的过程之后!对于我的图片,我收到此错误:ArgumentError(noimagesinthisimagelist):app/uploaders/image_uploader.rb:36:in`fix_exif_rotation'app/controllers/posts_controller.rb:12:in`create'Carrierwave在没有进程的情况下工作正常,但在添加进程后尝试上传图像时抛出错误。流程如下:process:fix_exif_rotationdeffix_exif_rotationmanipulate!do|image|

  6. ruby - :this means in Ruby on Rails? 是什么 - 2

    我是Ruby和RubyonRails世界的新手。我已经阅读了一些指南,但我在使用以下语法时遇到了一些麻烦。我认为在Ruby中使用:condition语法来定义具有某种访问器的类属性,例如:classSampleattr_accessor:conditionend隐式声明“条件”属性的getter和setter。当我查看一些Rails示例代码时,我发现以下示例我并不完全理解。例如:@post=Post.find(params[:id])为什么它使用这种语法访问id属性,而不是:@post=Post.find(params[id])或者,例如:@posts=Post.find(:all):

  7. ruby - ruby 中绑定(bind)对象的实际使用 - 2

    昨晚,我在思考我认为是高级ruby​​语言的功能,即Continuations(callcc)和Bindingobjects。我的意思是高级,因为我有静态类型的oo语言背景(C#、Java、C++),我最近才发现ruby​​,所以这些语言特性对我来说不是很熟悉。我想知道这些语言功能在现实世界中的用途是什么。根据我的经验,一切都可以用静态类型的oo语言来完成,但有时我不太同意。我想我在阅读SamRuby的那篇好文章时发现了Continuation的美妙之处/兴趣:http://www.intertwingly.net/blog/2005/04/13/Continuations-for-C

  8. ruby - 在 Mechanize 中使用 JavaScript 单击链接 - 2

    我有这个:AccountSummary我想单击该链接,但在使用link_to时出现错误。我试过:bot.click(page.link_with(:href=>/menu_home/))bot.click(page.link_with(:class=>'top_level_active'))bot.click(page.link_with(:href=>/AccountSummary/))我得到的错误是:NoMethodError:nil:NilClass的未定义方法“[]” 最佳答案 那是一个javascript链接。Mechan

  9. ruby - 无法加载此类文件——脚本/rails : Getting this error while remote debugging through RubyMine - 2

    我在通过RubyMineIDE进行远程调试时遇到以下错误。$bundleexecrdebug-ide--port1234--script/railsserverFastDebugger(ruby-debug-ide0.4.9)listenson:1234/home/amit/.rvm/gems/ruby-1.9.3-p125/gems/ruby-debug-ide19-0.4.12/lib/ruby-debug-ide.rb:123:in`debug_load'/home/amit/.rvm/gems/ruby-1.9.3-p125/gems/ruby-debug-ide19-0.4.

  10. javascript - jQuery 的 jquery-1.10.2.min.map 正在触发 404(未找到) - 2

    我看到有关未找到文件min.map的错误消息:GETjQuery'sjquery-1.10.2.min.mapistriggeringa404(NotFound)截图这是从哪里来的? 最佳答案 如果ChromeDevTools报告.map文件的404(可能是jquery-1.10.2.min.map、jquery.min.map或jquery-2.0.3.min.map,但任何事情都可能发生)首先要知道的是,这仅在使用DevTools时才会请求。您的用户不会遇到此404。现在您可以修复此问题或禁用sourcemap功能。修复:获取文

随机推荐