0

I have a problem with scopes (global variables/namespaces) that i just can't fix. The thing is that I have some legacy code on a project in which i added new functionalities using Require.js. This legacy code is loaded using standard <script> tags, but the new code is loaded with Require. The problem occurs when I add the Ractive.js in Require as AMD. Because legacy code loads Prototype.js, it has some clashes with Ractive.js.

The main problem is when observing the array for changes. Specifically, when i observe the array with pattern observer.

ractive.observe('dataArray.*', function(newValue, oldValue, keypath) { alert(' status changed from ' + oldValue + ' to ' + newValue); }, {debug: true, init: false});

If i don't add observer to array, everything works, but if I add it, i get an error undefined is not a function in prototype.js (this doesn't happen when I remove prototype.js from globals).

Another this is that it actually works when i don't use the pattern observer.

So, my question is, is there a way to configure Require.js to use only the scripts that are loaded as AMD-s? Or, in other words, restrict the scope of AMD scripts to only each other so it ignores global scripts?

Thanks in advance.

4

1 回答 1

1

通过将旧版本的 Prototype.js 添加到页面,我能够创建类似的错误。我怀疑这是因为 Prototype.js 添加了非标准方法Array.prototype(除其他外)。这通常被认为是一件坏事,因为它使此类冲突在大型代码库中很可能发生。

具体来说,错误在于 RactiveArray.prototype.map在处理模式观察者时调用了一个字符串。该map函数在 ES5 中是标准的,但在旧版浏览器(例如 IE8)中没有,因此 Prototype 添加了一个 polyfill - 但在旧版本的 Prototype 中它是一个损坏的 polyfill。当您使用字符串而不是错误(因为它使用自己的this.each()方法)调用它时,损坏的 polyfill 会引发错误——这是 ES5 中不寻常但完全可以接受的操作。

幸运的是,看起来新版本的 Prototype 并没有以同样的方式被破坏。我能够使用 1.6.1(他们的文档网站上的版本,从 2009 年开始)重现该错误,但不能使用最新的 1.7.2 版本。

所以你有两种可能的选择:

  • 将原型升级到最新版本
  • 加载原型后,覆盖损坏的map()方法。你可以使用MDN 的这个 polyfill(确保你省略了if (!Array.prototype.map){...}检查)。

其中,第二种可能最不可能破坏依赖 Prototype 的代码!

于 2014-05-01T21:18:04.103 回答