1

I need help. I have this code. I have many sources and i don't use n*source watchs. I thinked that a for can be a solution, but the watch is instantiated and it dont read my source[i].

You can say some solutions.

Thnks!

var base_source = '../';
var source = ['dir1', 'dir2'];
var allFiles = '/**/*';
var dest = '../dist';

gulp.task('default', function () {

      for(var i = 0; i < source.length ; i++) {
        var watchW = base_source + source[i] + allFiles;

        gulp.watch(watchW, function(obj){
          copyFiles(watchW, dest , obj);
        });

      }
    }

Edit: I need the source[i] in copyFiles function

Sorry for my english ^^"

Cynth S.B.
  • 33
  • 3

1 Answers1

0

It is difficult to explain why your code doesn't work. As you can see only the last index "i" is bound to all watch functions. This is known as the "reference problem". All your watch functions are using, by reference, the same index i. See, for example, referencing last index in loop.

Using @OverZealous's answer as guidance in creating gulp tasks in a loop here is a solution for you:

var gulp = require('gulp');

// changed to up one directory
var base_source = './';

// changed variable name slightly for clarity
var sources = ['dir1', 'dir2'];
var allFiles = '/**/*';

// changed to up one directory
var dest = './dist';

var watchSources = Object.keys(sources);

gulp.task('default', function () {

  watchSources.forEach(function (index) {

    var watchW = base_source + sources[index] + allFiles;

    gulp.watch(watchW, function (obj) {
      copyFiles(watchW, dest, obj);
    });
  });
});

function copyFiles(watched, to, obj)  {
  console.log("watched = " + watched);
}
Mark
  • 143,421
  • 24
  • 428
  • 436