我正在使用 requireJs 进行依赖管理。
地址.js
define(["jquery"], function($) {
//private fields
var $name = null;
var $number = null;
var $street = null;
var $suburb = null;
var initialisationAttempts = 0;
return new function() {
//public fields
/**
* initialise for first use
*/
this.init = function(fields) {
if(initialisationAttempts > 0) {
console.log('ERROR: Address has been initialised (' + ++initialisationAttempts + ') times!');
} else {
$name = fields.$name;
$number = fields.$number;
$street = fields.$street;
$suburb = fields.$suburb;
initialisationAttempts++;
}
};
/**
* Clean all form fields
*/
this.clear = function () {
$name.val('');
$number.val('');
$street.val('');
$suburb.val('');
};
};
});
我有两种不同的地址实现
fromAddress.js
define(['page/lib/address', 'jquery'], function(address, $) {
fromFields = {
$name: $("#from-address-name"),
$number: $("#from-address-number"),
$street: $("#from-address-street"),
$suburb: $("#from-address-suburb"),
};
address.init(fromFields);
return address;
});
toAddress.js
define(['page/lib/address', 'jquery'], function(address, $) {
fromFields = {
$name: $("#to-address-name"),
$number: $("#to-address-number"),
$street: $("#to-address-street"),
$suburb: $("#to-address-suburb"),
};
address.init(fromFields);
return address;
});
如果我称这些是序列
(function() {
require(['jquery', 'page/lib/fromAddress', 'page/lib/toAddress'], function ($, fromAddress, toAddress) {
$(document).ready( function() {
//clear all input fields
fromAddress.clear();
toAddress.clear();
});
});
})();
调用toAddress.clear()
无法运行该init
函数,因为它已被fromAddress
对象调用(我在方法中收到“错误”消息init
)。我希望 toAddress 和 fromAddress 对象引用不同的地址对象,我该如何实现呢?
更新:
根据建议,我已将代码修改如下,并且似乎可以正常工作。
地址.js
define(["jquery"], function($) {
return function(fields) {
//public fields
/**
* Clean all form fields
*/
this.clear = function () {
fields.$name.val('');
fields.$number.val('');
fields.$street.val('');
fields.$suburb.val('');
fields.$suburb.css("background-color", fields.colour);
};
};
});
fromAddress.js
define(['jquery', 'page/lib/address'], function(jq, address) {
fields= {
$name: jq("#from-address-name"),
$number: jq("#from-address-number"),
$street: jq("#from-address-street"),
$suburb: jq("#from-address-suburb"),
colour: 'green',
};
return new address(fields);
});
toAddress.js
define(['jquery', 'page/lib/address'], function(jq, address) {
fields= {
$name: jq("#to-address-name"),
$number: jq("#to-address-number"),
$street: jq("#to-address-street"),
$suburb: jq("#to-address-suburb"),
colour: 'red',
};
return new address(fields);
});