6

私はjqueryでjsdomを使用していますが、問題なく動作しています。ただし、コードを少しモジュール化しようとしているので、繰り返しません。そこで、html(DOM)を取り込んでjqueryで微調整し、吐き出すjsdomコードから基本的な関数を作成しました。 。ただし、結果を返すことができないため、呼び出し元の変数に割り当てることができません。私はおそらく正しい場所に戻っていないでしょうが、そうだとすれば明らかなことはわかりません。少し助けを使うことができます。

コードは次のとおりです。

function tweakIt(html_in){
  var jsdom = require('jsdom');
  jsdom.env({
    html: html_in,
    scripts: [
      '../public/javascripts/jquery-1.7.1.min.js',
    ],
    done: function(errors, window) {
      var $ = window.$;
      // do some jquery magic and manipulate the dom
      $('body').append('<div>foo</div>');

      console.log('Freshly Manipulated HTML: '+ $('body').html()); // it logs perfectly
      return $('body').html(); // this isn't returned to where I called tweakIt() from, why not?
    }
  });
}

var oldhtml = '<html><body><div>some text</div></body></html>';
var newhtml = tweakIt(oldhtml); // never gets set because nothing gets returned, why?

編集:

これは確かに非同期の問題だったので、リターンの代わりにコールバックを使用して行う方法は次のとおりです。

function tweakIt(html_in, callback){
  var jsdom = require('jsdom');
  jsdom.env({
    html: html_in,
    scripts: [
      '../public/javascripts/jquery-1.7.1.min.js',
    ],
    done: function(errors, window) {
      var $ = window.$;
      // do some jquery magic and manipulate the dom
      $('body').append('<div>foo</div>');

      console.log('Freshly Manipulated HTML: '+ $('body').html()); // it logs perfectly
      callback($('body').html()); // instead of a return, pass the results to the callback
    }
  });
}

var oldhtml = '<html><body><div>some text</div></body></html>';
var newhtml = tweakIt(oldhtml, function(newstuff){
  console.log(newstuff); // woohoo! it works!
});
4

2 に答える 2

5

I don't think you can do this using a return value, because done: is an async function. Try adding a callback to your tweakIt and get the new html by sending it as a parameter, e.g.

tweakIt(oldHtml, function(newHtml) {/*use the result here*/})

于 2012-02-23T18:59:58.380 に答える