我有一个节点列表,它们是 html li 元素
<ul id="nodesList">
<li id="node_1">Node 1</li>
<li id="node_2">Node 2</li>
<li id="node_3">Node 3</li>
<li id="node_4">Node 4</li>
<li id="node_5">Node 5</li>
</ul>
我有一个管理这些节点的 javascript 函数
(function (nodesManager) {
var nodes = [];
nodesManager.requestNode = function(id) {
if (nodes[id]) {
return nodes[id];
}
nodes[id] = new Node(id);
return nodes[id];
}
} (window.nodesManager = window.nodesManager || {}));
var Node = function(id) {
instance = this;
var node = $("#node_" + id);
this.changeName = function(newValue) {
node.text(newValue);
};
// and other nodes specific functions
var _properties = null;
this.getProperties = function () {
if (_properties !== null)
return _properties;
var response = null;
$.ajax({
cache: false,
async: false,
type: "GET",
url: '/Nodes/NodeProperties', // json object { "dateCreated": "10 minutes ago", "createdBy": "Mike" }
data: { node_Id: id },
success: function (data, textStatus) {
if (data.hasError) {
alert(data.message);
} else {
response = data;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('ajax error');
}
});
_properties = response;
return _properties;
};
this.resetProperties = function () {
_properties = null;
};
}
$("#nodesList").delegate("li", "click", function() {
var node_Id = $(this).attr("id").replace("node_", "");
var newNodeName = "I am a new value";
nodesManager.requestNode(node_Id).changeName(newNodeName);
});
我的问题是,如果 Node 对象中的 changeName 函数会影响性能?
它是为用户选择的每个节点创建的吗?
将它放在 nodesManager 函数中是否更好,因此它只实例化一次?或者这没关系...
什么对我来说很重要
function getNodeCreatorUserName(id) {
var properties = nodesManager.requestNode(id).getProperties();
var userName = properties.createdBy;
// do something with userName
};
function getNodeDateCreated(id) {
var properties = nodesManager.requestNode(id).getProperties();
var dateCreated = properties.dateCreated;
// do something with dateCreated
};
getNodeCreatorUserName("1");
getNodeDateCreated("1"); // No server side call will be made because properties are already stored in Node object