2012-04-25 26 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

請接受的答案,如果它是令人滿意的,或者突出顯示您需要幫助,歡呼聲任何進一步的問題:) – 2012-05-02 15:49:29

回答

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(); 
});