更新
如果要更新了一系列的实例,使许多Ajax请求,那么你需要看的Ajax长轮询和排队技术。您将无法保留引用,但无论您使用何种Ajax技术,都可以使用下面的技巧来保留引用。
在顶部添加长轮询,你很好去。
的想法是这样的:
假定服务器会以JSON格式响应。如果你需要参考原始参考文献,这里是我的两分钱:
更新服务器回复时的确切参考。假设您有10个存储在数组中的Something
实例。在成功响应时,您可以使用Something
类中的方法以任何您想要的方式更新特定实例。
/**
* The array with something instances.
* @type {Array.<Something>}
*/
var instances = [];
/**
* The Ajax success function.
* @param {Event} event The event object.
*/
function ajaxSuccess(event) {
var response = event.target.getResponseText();
var actualResponse = JSON.parse(response);
for (var i = 0, len = actualResponse.length; i++) {
instances[i].setWhatever(actualResponse[i].whatever);
};
};
以上是更为程序化的方法。如果你想在JS中完全生成OOP,那么你可以考虑采用模块化设计模式。假设你有一个将数据加载到某个地方的模块。基本上,与该模块相关的所有内容都是一个实例属性。
var myModule = function() {
this.whatever = 1;
};
myModule.prototype.loadMore = function() {
var request = new XMLHttpRequest(),
that = this; // store a reference to this.
request.send(); // etc
request.onreadystatechange = that.onSucess;
};
myModule.prototype.onSucess = function(event) {
var response = JSON.parse(event.target.getResponseText());
this.whatever = response.whatever;
};
var moduleInstance = new myModule();
myModule.loadMore();
// Now the scope is always preserved. The callback function will be executed in the right scope.
让我们假设在事物的后端,有一个模拟类模仿您的客户端JavaScript模型。假设你想在显示文本的模型中更新引用。我在后端使用Scala,但查看字段/属性并忽略语法。
case class Article (
title: String,// these are my DB fields for an Article.
punchline: String,
content: String,
author: String
);
// now assume the client is making a request and the server returns the JSON
// for an article. So the reply would be something like:
{"title": "Sample title", "punchline": "whatever", "content": "bla bla bla boring", "author": "Charlie Sheen"};
// when you do
var response = JSON.parse(event.target.getResponseText());
// response will become a JavaScript object with the exact same properties.
// again, my backend choice is irrelevant.
// Now assume I am inside the success function, which gets called in the same scope
// as the original object, so it refers TO THE SAME THING.
// the trick is to maintain the reference with var that = this.
// otherwise the onSuccess function will be called in global scope.
// now because it's pointing to the same object.
// I can update whatever I want.
this.title = response.title;
this.punchline = response.punchline;
this.content = response.content;
this.author = response.author;
// or I can put it all in a single variable.
this.data = response;
您需要记住的是该范围需要保留。这就是诀窍。 当我做var that = this;
我复制对模型实例的引用。该参考文献通过更高阶而不是目前的范围记住。
然后我告诉XMLHttpRequest
对象在完成时调用that.ajaxSuccess
。因为我使用了that
,所以ajaxSuccess
函数将在当前对象的范围内调用。所以在ajaxSuccess
函数里面,this
会指向原来的this
,同样的实例。
的JavaScript记得它对于我来说,当我写var that = this;
你能表现出一定的代码是如何被创建的对象? – deceze 2013-04-29 10:15:31
向我们展示序列化代码,我们可以帮助您完成相反的操作。 – Bergi 2013-04-29 11:56:35