2012-04-25 2 views
1

Я переношу один из моих старых файлов javascript в совместимый с requireJS. Ранее это выглядит как код.Как сделать этот модуль совместимым с requireJS

// effect.js 
(function(exports){ 

    // shorthand 
    exports.effect = function(selector) { 
     return new Effect(selector); 
    }; 

    // init 
    exports.Effect = function(selector){ 
     this.target = document.getElementById(selector);   
    }; 

    Effect.prototype.run = function(){ 
     alert('halo'); 
    }; 
})(this); 

//invoke it with 
effect('box').run(); 

Пытался сделать его совместимым с requireJS:.

// effect.js 
define(function(exports){ 
    // Shorthand 
    exports.effect = function(selector) { 
     return new Effect(selector); 
    }; 

    // init 
    exports.Effect = function(selector){ 
     alert('halo'); 
     this.target = document.getElementById(selector);   
    }; 

    Effect.prototype.run = function(){ 
     alert('halo'); 
    };  
} 

// require js 
require([ 
    'effect.js' 
],function(Effect){ 
    effect('box').run(); 
}) 

Код выше не будет работать, как я могу добиться того же результата с просто работает сокращенную эффекта («коробки») запустить().

+0

Пожалуйста, примите ответ, если он был удовлетворительным, или выделить какие-либо дополнительные вопросы, Вам нужна помощь, ура :) –

ответ

2

Дайте это попробовать:

define(function() { 

    // init 
    var Effect = function(selector) { 
     this.target = document.getElementById(selector); 
    }; 

    Effect.prototype.run = function(){ 
     alert('halo'); 
    }; 

    // Replaces the 'shorthand' function from the first example 
    // This is returned as a module to the require call 
    return function(selector) { 
     return new Effect(selector); 
    } 

}); 

require(['effect.js'], function(effect) { 
    effect('box').run(); 
}); 
Смежные вопросы