Back

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

发布时间: 2014-07-26 08:31:00

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

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

总之,它有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!')
      }
    })

Back