可以观察到Knockoutjs和jQuery扩展功能 [英] Knockoutjs observable and jQuery extends function
问题描述
假设我有以下代码:
var Klass = function(){
var self = this;
this.value = 123;
this.update = function(){
$.ajax({
url: '/whatever',
async: false,
success: function(data){
$.extend(self, data);
}
});
}
}
假设,'/whatever'返回此json对象:
Lets assume, '/whatever' returns this json object:
{value: 234}
当我这样做时:
var obj = new Klass();
obj = ko.mapping.fromJS(obj);
console.log(obj);
我们都知道obj
现在是可以观察到的淘汰赛.
We all know obj
is now an knockoutjs observable.
我运行这个:
obj.update();
console.log(obj);
我发现,obj
的值不会被覆盖为简单值234,而是作为可观察的属性保留.
What I have discovered is, value of obj
doesn't get overridden as a simple value 234, but stayed as an observable property.
我的问题是:
1)为什么会这样?
2)我如何根据需要进行更新.
2) How do I make the update work as I wanted.
更新:ajax调用不是异步的.
UPDATE: ajax call is not asynchronous.
推荐答案
第一个问题是您要扩展self
,它是一个有作用域的变量,仅存在于Klass函数内部,而不是您通过调用它创建的实例.
First issue is that you are extending self
, which is a scoped variable and only exists inside the Klass function, not it's instances you create by calling it.
如果在调用update
时需要覆盖value
,则需要调用$.extend(this, data);
.
尽管我确实理解您为什么在这里使用self
.
但是随后会丢失通过调用ko.mapping.fromJS
添加的observable
功能. value
不再是一个函数(ko observable
),而是一个标量值(234
).您必须再次调用obj = ko.mapping.fromJS(obj);
才能将值包装为observable
.
You'll need to call $.extend(this, data);
if you need to overwrite value
when calling update
.
Although I do understand why you are using self
there.
But the observable
functionality added by calling ko.mapping.fromJS
is then lost. value
is no longer a function (ko observable
) but a scalar value (234
). You have to call obj = ko.mapping.fromJS(obj);
again to wrap value as observable
.
第二个问题是$.get
是异步,所以正确调用console.log(obj)
调用obj.update
之后,将记录GET响应之前的值.您需要等待它执行(使用回调).
Second issue is that $.get
is asynchronous so calling console.log(obj)
right after calling obj.update
will log the value before the GET response comes. You need to wait for it to execute (use a callback).
这是一个正常工作的小提琴.
var Klass = function(){
this.value = 123;
this.update = function(callback){
var self = this;
$.get('/', function(data) {
$.extend(self, {value: 234});
callback.call(undefined);
});
}
}
var obj = new Klass();
obj = ko.mapping.fromJS(obj);
console.log(obj.value());
obj.update(function() {
obj = ko.mapping.fromJS(obj);
console.log(obj.value());
});
这篇关于可以观察到Knockoutjs和jQuery扩展功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!