0
我想通过访问从json使用jquery-ajax填充的列表来呈现骨干视图。如何从外部json文件中获取数据到骨干视图
我面临的问题是,即使在ajax调用完成之前,页面也会呈现。我不确定是否可以在成功数据中包含主干模型/视图,以便在获取数据后使其工作。如果我替换ajax调用并将静态json写入一个javascript变量,那么这将工作正常。但是我无法通过外部电话获得此功能。
我使用的方法可能不正确,我想要一个正确的方法来使用主干。
代码如下:
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script class="jsbin" src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script class="jsbin" src="http://documentcloud.github.com/backbone/backbone.js"></script>
<script>
var stages;
$.ajax({
type: 'GET',
url: 'test.php',
async:'false',
data: { get_param: 'value' },
success: function (data) {
window.stages = data;
alert(stages);
}
});
alert(stages);
// StageModel: no need to extend if you're not adding anything.
StageModel = Backbone.Model;
// StageCollection
StageCollection = Backbone.Collection.extend({
model: StageModel
});
// create view for list of stages
StageCollectionView = Backbone.View.extend({
el: $("#stageNav"),
initialize: function() {
this.collection.bind('add', this.createStageListItem, this);
},
events: {
'click .stageListItem' : 'selectStage'
},
createStageListItem: function(model) {
this.$("#stageList").append("<tr><td id=\"" + model.cid + "\" class='stageListItem'>" + model.get('label') +'</td><td>-'+ model.get('message') + "</td></tr>");
},
selectStage: function(event) {
var cid = $(event.target).attr('id');
this.trigger('new-stage', this.collection.getByCid(cid));
},
render: function() {
var self = this;
this.collection.each(function(model) {
self.createStageListItem(model);
});
return this;
}
});
// StageView,
StageView = Backbone.View.extend({
el: $("#stage"),
initialize: function(options) {
this.eventSource = options.newStageEventSource;
this.eventSource.bind('new-stage', this.loadAndRenderStage, this);
},
load: function(model) {
this.model = model;
return this;
},
render: function() {
$("#stageLabel").html(this.model.get('label'));
$("#stageMsg").html(this.model.get('message'));
},
loadAndRenderStage: function(stage) {
this.load(stage);
this.render();
}
});
var stageCollection = new StageCollection(stages);
var stageCollectionView = new StageCollectionView({
collection: stageCollection
});
var stageView = new StageView({
newStageEventSource: stageCollectionView
});
stageCollectionView.render();
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id="stageNav">
<table id="stageList">
</table>
</div>
<div id="stage">
<h3 id="stageLabel"></h3>
<p id="stageMsg"></p>
</div>
</body>
</html>
非常感谢
罗伊