我目前正在开发一个Web应用程序,我们使用模型视图控制器方法来组织我们的信息和代码。在我们的例子中,我们将View和Controller组合成一个Javascript文件,模型是独立的。
我的问题来了。我在我的模型中有原型对象,但我想在我的viewcontroller Javascript文件中实例化这些对象的实例。我如何让他们互相交谈?
答案 0 :(得分:0)
有一些方法可以实现这一目标。今天,最简单的是:
<script src='model.js'></script>
<script src='view-controller.js'></script>
因此,由于您的model.js将首先被加载,您可以在视图/控制器中使用它。
另一种方法是使用模块。今天使用最多的是RequireJS。 E.g:
require(['model'], function(model) {
// This function is called when model.js is loaded.
// If model.js calls define(), then this function is not fired until
// model's dependencies have loaded, and the model argument will hold
// the module value for model.js.
});
ECMAScript 6(Javascript的下一个版本)将有native modules,因此您将能够:
import * as model from './model'
var x = model.variable; // etc
答案 1 :(得分:0)
如果您熟悉Node和RequireJS,您可能还需要考虑使用Browserify,因为您也在前端使用NPM模块。 http://browserify.org/
Browserify允许您从一个文件中导出JS代码,并在另一个文件中使用它(简化的想法)。
文件1:myfunc.js
var myFunc = function(){
console.log("I'm an exported function that's in another file");
};
module.exports = myFunc;
文件2:app.js
var myFunc = require('./myfunc.js');
myFunc(): // logs "I'm an exported function that's in another file"