node 中的 context / scope ( node-webkit context)

访问量: 4302

node 中,每段js 都会有自己的 context  . 这点理解起来跟ruby, raw html/js很不一样。

看看官方的说法: (https://github.com/rogerwang/node-webkit/wiki/Differences-of-JavaScript-contexts

  • If the require() method (of Node.js modules API) is used, then the required module runs in the Node's context. (When you call the require() function or a function from some required module, the JS engine enters the Node's context and leaves it after the function returns.)
  • If HTML <script src="..."> element (or jQuery's $.getScript(), or any other similar method) is used in some window, then the script runs in the context of that window.
  • If the module is given as the value of the "node-main" property of the application's manifest file, then the module runs in the Node's context but later has access to the window object. (See the “node-main” article for details.)

总之,它有3个不同的 context  。 实际上用起来是这个效果:

想让JS在全局生效, 需要在package.json 中设置 'node-main' 这个属性, 例如

1. package.json

{
  "name": "nw-demo",
  "node-main": "index.js",
  "main": "index.html"
}

2 .index.js:

var i = 0;
exports.callback0 = function () {
    console.log(i + ": " + window.location);
    window.alert ("i = " + i);
    i = i + 1;
}

3. 最后,在HTML中引用这个方法:

<body onload="process.mainModule.exports.callback0()">

但是,如果在  index.js 中引入 jQuery, 会报错:  jquery 需要一个 window, document啥啥的。

所以, 我们需要下面的代码:  (也就是说,每一个HTML都要有自己的 $ = require('jquery') ) 

  <div id='target_site'></div>
  <script>
    url = 'http://siwei.me'
    $ = require('jquery')
    request = require('request')
    request(url, function(error, response, body){
      if (!error && response.statusCode == 200 ) {
        $('#target_site').html(body)
        //console.info(body)
        alert('ok!')
      }
    })

订阅/RSS Feed

Subscribe

分类/category