문제

I'm attempting to fix a bookmarklet I wrote to track the URL changes in a single page application, specifically recording timesheet while using asana. It uses a script loader to embed jQuery and KnockoutJS libraries before init. I'm unable to find the ko object in global scope after the KnockoutJS library has initialized and cannot figure out why. To test, login to https://app.asana.com, open the Google Chrome developer tools' Console tab and try the following code:

var koScript=document.createElement('script');
koScript.type='text/javascript';
koScript.src='//ajax.aspnetcdn.com/ajax/knockout/knockout-3.0.0.js';
document.getElementsByTagName('head')[0].appendChild(koScript);

The Network tab shows the script downloading. The Elements tab shows the script as the last child of the head element. Yet ko remains undefined.

도움이 되었습니까?

해결책

The short version is that:

  1. Asana uses an internal module system that uses module.exports and require - the CommonJS standard you may know from node.js.
  2. The knockout.js file checks the environment to determine if it should be setting window.ko or using module.exports or AMD-style define. If it detects CommonJS-style require it sets properties on exports instead of on a global ko object.

Workaround:

You could temporarily "copy" require off first:

_require = require; require = null

And then it should set window.ko as you're expecting!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top