我有一个这样的例子,用于在viewmodel(observable)类构造函数中定义的本地值,但是当你有一个远程数据源时它似乎不起作用。
我怎么能得到一个类似于下面为远程数据源工作的例子,它甚至可能吗?
<div id='root'>
<label>Remote Name: </label>
<span data-bind="text: firstName"><!--firstName--></span>,
<span data-bind="text: lastName"><!--lastName--></span>
<div>
<label>Remote Name:
<input data-bind="value: firstName" />,
<input data-bind="value: lastName" />
</label>
</div>
</div>
<br/>
<br/>
<div id='local-root'>
<label>Local Name: </label>
<span data-bind="text: firstName"></span>,
<span data-bind="text: lastName"></span>
<div>
<label>Local Name:
<input data-bind="value: firstName" />,
<input data-bind="value: lastName" />
</label>
</div>
</div>
<br/>
<br/>
<div id='test-ajax'>
<pre>
</pre>
</div>
$(document).ready(function(){
/**
* #local-root example, binds to local data like in the examples
*/
var personLocalViewModel = kendo.observable({
firstName: 'James',
lastName: 'Taylor'
});
kendo.bind($('#local-root'), personLocalViewModel);
/**
* set's up a mock api endpoint for jquery and other libraries
*/
$.mockjax({
url: "js/data/person.json",
contentType: "application/json",
responseText: {
firstName: 'James',
lastName: 'Taylor'
}
});
/**
* test-ajax - proves mockajax works
*/
$.ajax({
url: "js/data/person.json",
dataType:'json',
success:function(response){
$('#test-ajax pre').text(JSON.stringify(response));
}
});
/**
* #root or remote-root, this dataSource is not bidning to the html, why?
*/
console.log('KENDO.js', kendo.data);
var personSource = new kendo.data.DataSource({
transport: {
read: {
url: "js/data/person.json",
dataType: "json"
}
},
schema:{
parse: function(response){
console.log('personSource.schema.parse',response);
return response;
},
data: function(response){
console.log('personSource.schema.data',response);
return response;
}
}
});
//would this work?
var personViewModel = kendo.observable({
dataSource: personSource
});
//would this work?
var personViewModel2 = kendo.observable(personSource);
kendo.bind($('#root'), personViewModel);
});
答案 0 :(得分:6)
DataSource希望对一组记录进行操作。我相信你可以用解析或模式解决这个问题,但是对于这个例子,我改变了模拟ajax调用以返回一个数组。
$.mockjax({
url: "js/data/person.json",
contentType: "application/json",
responseText: [{
firstName: 'James',
lastName: 'Taylor'
}]
});
第一个问题是您设置数据源但从不填充数据。我添加了对.read()
personSource.read();
当我将responseText更改为数组时,我更新了与此类似的绑定:
data-bind="text: dataSource.view()[0].firstName"